【问题标题】:How I can access a file with c#? [duplicate]如何使用 c# 访问文件? [复制]
【发布时间】:2019-09-12 17:55:48
【问题描述】:

有一些函数可以在不使用 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();
}

【问题讨论】:

  • 您只需要所有文本吗?如果是这样,请参阅File.ReadAllText。也请查看File.ReadAllLines。两者都有异步变体。
  • 是的,我需要使用 File.ReadAllText 重新读取所有文本。

标签: c#


【解决方案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);
}

【讨论】:

    猜你喜欢
    • 2013-05-15
    • 2021-03-31
    • 1970-01-01
    • 2020-06-02
    • 2022-01-14
    • 1970-01-01
    • 2011-06-13
    • 1970-01-01
    • 2020-06-20
    相关资源
    最近更新 更多