2017-01-09 74 views
-5
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); 
      } 

     } 
    } 
} 
+5

您忘記了描述問題或提出問題的部分。只有代碼 – David

+0

,毫無疑問,這不是一個好的開始。請看看[我如何問一個好問題?](http://stackoverflow.com/help/how-to-ask) –

+0

使用[WriteAllBytes](https://msdn.microsoft.com/en- us/library/system.io.file.writeallbytes(v = vs.110).aspx)而不是WriteAllText。 [這個問題](http://stackoverflow.com/questions/472906/how-do-i-get-a-consistent-byte-representation-of-strings-in-c-sharp-without-manu)顯示如何將你的字符串轉換爲一個字節數組。 – stuartd

回答

2

首先建立一些佔位二進制擴展:

if (filename.EndsWith(BINARY_EXTENSION)) 
    File.WriteAllBytes(filename, Encoding.UTF8.GetBytes(tbEditor.Text)); // Or choose something different then UTF8 
else 
    File.WriteAllText(filename); 

而且裏面:

const string BINARY_EXTENSION = "bin"; 

btnSaveFile_Click()您可以修改保存功能你的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); 
+0

謝謝,這工作! –

+0

將2個不同版本的文本保存爲UTF8有什麼意義?它絕對沒有理由使代碼變得複雜 - 只有相同的TXT代碼和神祕的「二進制」BIN格式。爲了讓回答有些合理,你可能想解釋一下你的「二進制」格式是什麼以及它與另一個格式有什麼不同。 –

+0

@AlexeiLevenkov這就是爲什麼我寫了'//或者選擇了不同於UTF8的東西'這意味着要選擇不同的方法來從文本中「提取」字節。 –

相關問題