WPF & C# - 간단한 메모장 Memo ( OpenFileDialog / SaveFileDialog / StreamReader / StreamWriter / NotePad / 노트패드 )

2018. 8. 2. 12:01Programing (프로그래밍)/WPF & C# (C Sharp)

728x90
반응형


 WPF & C# - 간단한 메모장 Memo ( OpenFileDialog / SaveFileDialog / StreamReader / StreamWriter / NotePad / 노트패드 )



Memo.zip




MainWindow.xaml



1
2
3
4
5
6
7
8
9
10
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="80"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="80"/>
    </Grid.RowDefinitions>
    <Button Grid.Row="0" x:Name="btnOpen" Margin="5" Content="Open" Click="open"></Button>
    <TextBox Grid.Row="1" x:Name="txt" Margin="5" AcceptsReturn="True" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto"></TextBox>
    <Button Grid.Row="2" x:Name="btnSave" Margin="5" Content="Save" Click="save"></Button>
</Grid>
cs





MainWindow.xaml.cs



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
public MainWindow()
{
    InitializeComponent();
    this.Title = "WPF 메모장";
}
 
string file = "";   // 파일 Path
 
private void open(object sender, RoutedEventArgs e)
{
    // 파일 열기, OpenFileDialog
    OpenFileDialog ofdlg = new OpenFileDialog();
    {
        ofdlg.Filter = // 필터설정
            "txt File | *.txt";
 
        ofdlg.CheckFileExists = true;   // 파일 존재여부확인
        ofdlg.CheckPathExists = true;   // 폴더 존재여부확인
 
        // 파일 열기 (값의 유무 확인)
        if (ofdlg.ShowDialog().GetValueOrDefault())
        {
            file = ofdlg.FileName;
            this.Title = file;
 
            using (StreamReader sw = new StreamReader(file))
            {
                txt.Text = sw.ReadToEnd();
            }
        }
    }
}
private void save(object sender, RoutedEventArgs e)
{
    // 파일 저장
    if (file == "")
    {
        SaveFileDialog sfdlg = new SaveFileDialog();
        sfdlg.Filter = // 필터설정
            "Text File | *.txt";
 
        if (sfdlg.ShowDialog().GetValueOrDefault())
        {
            file = sfdlg.FileName;
            this.Title = file;
        }
        else return;
    }
 
    // StreamWriter(파일명, 내용추가여부(false 는 다 지우고 새로쓴다.), 인코딩)
    using (StreamWriter sw = new StreamWriter(file, falseEncoding.UTF8))
    {
        sw.Write(txt.Text);
    }
}
cs




728x90
반응형