728x90
반응형
WPF & C# - 간단한 메모장 Memo ( OpenFileDialog / SaveFileDialog / StreamReader / StreamWriter / NotePad / 노트패드 ) |
MainWindow.xaml
<Window x:Class="testSaveFileDialog.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:testSaveFileDialog"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<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>
</Grid>
</Window>
MainWindow.xaml.cs
public MainWindow()
{
InitializeComponent();
this.Title = "간단한 메모장";
}
string file = "";
private async void Save(object sender, RoutedEventArgs e)
{
await SaveFile("Memo", txt.Text);
}
private async void Open(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog { Filter = "텍스트 파일 (*.txt;*.log)|*.txt;*.log" };
if (openFileDialog.ShowDialog() == true)
{
string filePath = openFileDialog.FileName;
try
{
txt.Text = await ReadFileAsync(filePath, TimeSpan.FromSeconds(0.5));
}
catch (IOException ex)
{
MessageBox.Show($"파일을 열 수 없습니다: {ex.Message}", "오류", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
private async Task<string> ReadFileAsync(string filePath, TimeSpan timeout)
{
// 액세스 불가능한 파일은 FileAccess.Read 으로 오픈
using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (StreamReader reader = new StreamReader(stream))
{
Task<string> readTask = reader.ReadToEndAsync();
Task completedTask = await Task.WhenAny(readTask, Task.Delay(timeout));
if (completedTask == readTask)
{
return await readTask;
}
else
{
throw new TimeoutException($"File read operation timed out after {timeout.TotalSeconds} milliseconds.");
}
}
}
}
private async Task SaveFile(string defaultFileName, string content)
{
SaveFileDialog saveFileDialog = new SaveFileDialog
{
FileName = defaultFileName,
Filter = "텍스트 파일 (*.txt)|*.txt"
};
if (saveFileDialog.ShowDialog() == true)
{
string filePath = saveFileDialog.FileName;
try
{
using (StreamWriter writer = new StreamWriter(filePath))
{
await writer.WriteAsync(content);
}
}
catch (IOException ex)
{
MessageBox.Show($"파일을 저장하는 중 오류가 발생했습니다: {ex.Message}", "오류", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
728x90
반응형