2016-01-08 57 views
1

我运行一个方法,是三个部分组成,第一部分和3都是“读文本文件”一样,C#读取写入文本文件结束在中东

和第2部分是保存串到文本文件,

// The Save Path is the text file's Path, used to read and save 
// Encode can use Encoding.Default 
public static async void SaveTextFile(string StrToSave, string SavePath, Encoding ENCODE) 
{ 
    // Part1 
    try 
    { 
     using (StreamReader sr = new StreamReader(SavePath, ENCODE)) 
     { 
      string result = ""; 
      while (sr.EndOfStream != true) 
       result = result + sr.ReadLine() + "\n"; 

      MessageBox.Show(result); 
     } 
    } 
    catch (Exception e) 
    { 
     Console.WriteLine(e); 
    } 

    // Part2 
    try 
    { 
     using (FileStream fs = new FileStream(SavePath, FileMode.Create)) 
     { 
      using (StreamWriter sw = new StreamWriter(fs, ENCODE)) 
      { 
       await sw.WriteAsync(StrToSave); 
       await sw.FlushAsync(); 
       sw.Close(); 
      } 
      MessageBox.Show("Save"); 
      fs.Close(); 
     } 
    } 

    // The Run End Here And didn't Continue to Part 3 

    catch (Exception e) 
    { 
     Console.WriteLine(e); 
    } 

    // Part3 
    try 
    { 
     using (StreamReader sr = new StreamReader(SavePath, ENCODE)) 
     { 
      string result = ""; 
      while (sr.EndOfStream != true) 
       result = result + sr.ReadLine() + "\n"; 

      MessageBox.Show(result); 
     } 
    } 
    catch (Exception e) 
    { 
     Console.WriteLine(e); 
    } 
} 

但我觉得奇怪的是,在这个地方的过程中到底哪里2部分完成,并且该过程结束,直接,但没有继续PART3,

是什么原因这个条件?一般过程应该贯穿整个方法但不应该停在中间

(还有一个问题) 还有其他方法可以做part2的目的吗,也可以继续part3来完成整个方法吗?

+0

有没有异常? – pquest

+0

这段代码是否在try/catch块中?可能你在它的中间有一个例外。 – jpgrassi

+0

不,即使我将三个使用块单独放在三个try catch中,该过程仍然在part2并在调试下结束,我没有看到它进入catch块 –

回答

1

问题是你告诉你的应用程序到await的方法,但从来没有得到任务结果或给它一个机会来完成。从到目前为止,你已经证明什么,你不需要异步的东西,无论如何,和大大简化代码:

public static void SaveTextFile(string StrToSave, string SavePath, Encoding ENCODE) 
{ 
    //Part1 
    try 
    { 
     MessageBox.Show(File.ReadAllText(SavePath, ENCODE)); 
    } 
    catch (Exception e) 
    { 
     Console.WriteLine(e); 
    } 

    //Part2 
    try 
    { 
     File.WriteAllText(SavePath, StrToSave, ENCODE); 
     MessageBox.Show("Save"); 
    } 
    catch (Exception e) 
    { 
     Console.WriteLine(e); 
    } 

    //Part3 
    try 
    { 
     MessageBox.Show(File.ReadAllText(SavePath, ENCODE)); 
    } 
    catch (Exception e) 
    { 
     Console.WriteLine(e); 
    } 
} 
+0

谢谢!对不起,我没有花更多的时间搜索关于readwritetext的更多方法,但这似乎是一个更好的方法 –

2

这可能是因为你正在编写一个异步方法无效,你是调用一些异步方法部分2.尽量在第2部分改变异步方法,以非异步方法:

using (StreamWriter sw = new StreamWriter(fs, ENCODE)) 
{ 
    sw.Write(StrToSave); 
    sw.Flush(); // Non-async 
    sw.Close(); // Non-async 
} 

它像现在期望的那样行事?

+0

我刚刚明白了,你是对的... –