2016-08-06 12 views
-1

私はアプリケーションの起動時にテキストファイルを保存し、このテキストファイルをアプリケーションの起動時から読み込んでいます。アプリケーションの起動時にFile.ReadAllText()を使用してテキストファイルを保存および読み込む方法

これはアプリケーションの起動時にファイルを保存していませんが、このコードで何が問題になっていますか?

アプリケーション起動コードでテキストファイルを保存します。

private void Savebutton1_Click(object sender, EventArgs e) 
    { 
     StreamWriter sw = new StreamWriter(Application.StartupPath + "Book.txt", true); 
     string json = JsonConvert.SerializeObject(vals); 

      sw.Write(json); 
      MessageBox.Show("Book Saved Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information); 

    } 

アプリケーションスタートアップコードからテキストファイルを読み込みます。

string path = Path.Combine(Application.StartupPath, "ChequeBook.txt"); 
      string textholder; 
      try 
      { 
       // Use StreamReader to consume the entire text file. 
       using (StreamReader reader = new StreamReader(path)) 
       { 
        MessageBox.Show("Reached Here"); 
        textholder = reader.ReadToEnd(); 
        MessageBox.Show("Reached Here - 2"); 
       } 

       if (textholder == string.Empty) { 

        return; 
       } 


       // Deserialise it from Disk back to a Dictionary 
       string jsonToRead = File.ReadAllText(textholder); 

       List<KeyValuePair<int, string>> myDictionaryReconstructed = 
        JsonConvert.DeserializeObject<List<KeyValuePair<int, string>>>(jsonToRead); 
+0

この1行のコードではどのような問題が発生しますか?おそらく、あなたの問題をよりよく理解するために、この行の周りにコードの部分を追加してください。 – Steve

+0

あなたはアプリケーションのパスを読むことができますhttp://stackoverflow.com/questions/837488/how-can-i-get-the-applications-path-in -a-net-console-applicationそしてそれをあなたのファイルと組み合わせてください –

+0

コンソールアプリケーションを実行しているようですが、すべての作業が完了したら終了します。これは、Console.ReadKey();のようなもので入力を要求することで終了しないでください。 – Crowcoder

答えて

1

私はFile.CreateTextメソッドを使用してアプリケーションフォルダ内の&書き込みテキストファイルを保存したかったです。

は、最初の答えが見つかりました:

これはアプリケーションフォルダ内のテキストファイルを作成し、保存します。

 using (StreamWriter sw = File.CreateText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Book.txt"))) 
     { 

      string json = JsonConvert.SerializeObject(vals); 
      sw.Write(json); 
     } 
     MessageBox.Show("Book Saved Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information); 

私はアプリケーションフォルダからテキストファイルを読み込みたいと思っていました。

これは、アプリケーションフォルダからテキストファイルの内容を読み取ります。

string jsonToRead = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Book.txt")); 
関連する問題