如何使用C#访问文件?

时间:2019-04-23 14:02:30

标签: c#

有一些函数可以不使用FileStream类而从文件中读取所有文本,并且更容易?

在Microsoft doc中,该代码可以从文件读取,但我认为有些复杂。

private async void Button_Click_1(object sender, RoutedEventArgs e)
{
    string filename = @"C:\Example\existingfile.txt";
    char[] result;
    StringBuilder builder = new StringBuilder();

    using (StreamReader reader = File.OpenText(filename))
    {
        result = new char[reader.BaseStream.Length];
        await reader.ReadAsync(result, 0, (int)reader.BaseStream.Length);
    }

    foreach (char c in result)
    {
        if (char.IsLetterOrDigit(c) || char.IsWhiteSpace(c))
        {
            builder.Append(c);
        }
    }
    FileOutput.Text = builder.ToString();
}

1 个答案:

答案 0 :(得分:1)

请参阅File.ReadAllText Method

public static void Main()
{
    string path = @"c:\temp\MyTest.txt";

    // This text is added only once to the file.
    if (!File.Exists(path))
    {
        // Create a file to write to.
        string createText = "Hello and Welcome" + Environment.NewLine;
        File.WriteAllText(path, createText, Encoding.UTF8);
    }

    // This text is always added, making the file longer over time
    // if it is not deleted.
    string appendText = "This is extra text" + Environment.NewLine;
    File.AppendAllText(path, appendText, Encoding.UTF8);

    // Open the file to read from.
    string readText = File.ReadAllText(path);
    Console.WriteLine(readText);
}