namespace SimpleTextEditor
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void btnOpenFile_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.DefaultExt = ".txt";
dlg.Filter = "Text documents (.txt) | *.txt";
Nullable<bool> result = dlg.ShowDialog();
if (result==true)
{
string filename = dlg.FileName;
tbEditor.Text = System.IO.File.ReadAllText(filename);
}
}
private void btnSaveFile_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.DefaultExt = ".txt";
dlg.Filter = "Text documents (.txt)|*.txt|Binary Files (.bin)|*.bin";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
string filename = dlg.FileName;
System.IO.File.WriteAllText(filename, tbEditor.Text);
}
}
}
}
答案 0 :(得分:2)
首先为二进制扩展创建一个占位符:
const string BINARY_EXTENSION = "bin";
在btnSaveFile_Click()
中您可以使用以下命令修改保存功能:
if ( filename.EndsWith(BINARY_EXTENSION))
File.WriteAllBytes(filename, Encoding.UTF8.GetBytes(tbEditor.Text)); // Or choose something different then UTF8
else
File.WriteAllText(filename);
在btnOpenFile_Click
内,您也可以这样做:
if ( filename.EndsWith(BINARY_EXTENSION))
tbEditor.Text = Encoding.UTF8.GetString(File.ReadAllBytes(filename); // Or choose something different then UTF8
else
tbEditor.Text = File.ReadAllText(filename);