C#读写文本文件以在中间结尾

本文关键字:在中间 结尾 文件 读写 文本 | 更新日期: 2023-09-27 18:29:23

我运行了一个方法,有三部分,第1部分和第3部分都是相同的"读取文本文件",

第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);
    }
}

但我觉得奇怪的是,这个过程在第二部分完成的地方结束,而这个过程直接结束,但没有在第三部分上继续

出现这种情况的原因是什么?一般来说,该过程应通过整个方法,但不应在中间停止

(还有一个问题)还有没有其他方法可以达到第二部分的目的,也可以继续到第三部分来完成整个方法?

C#读写文本文件以在中间结尾

这可能是因为您正在编写一个异步void方法,并且您正在调用第2部分中的一些异步方法。尝试将第2部分中的异步方法更改为非异步方法:

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

它现在的行为和你预期的一样吗?

问题是你告诉你的应用程序await方法,但从来没有得到Task结果,也没有给它完成的机会。从您目前所展示的内容来看,您无论如何都不需要异步的东西,并且大大简化了代码:

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);
    }
}