2017-01-09 4 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

コードのみですが、これは良いスタートではありません。 [よくある質問はどうすればよいですか]を見てください。 –

+0

[WriteAllBytes]を使用してください(https://msdn.microsoft.com/en-us/) writeAllTextの代わりにus/library/system.io.file.writeallbytes(v = vs.110).aspx)を使用します。 [この質問](http://stackoverflow.com/questions/472906/how-do-i-get-a-consistent-byte-representation-of-strings-in-c-sharp-without-manu)は、文字列をバイト配列に変換します。 – stuartd

答えて

2

まず、バイナリ拡張のためのいくつかのプレースホルダを作成します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とは別のものを選んでください。これは、テキストからバイトを抽出する別のメソッドを選択することを意味します。 –

関連する問題