-4

There are some function that read all text from file without use FileStream class and more easy?

In microsoft doc found this code to read from file but I think is some complexed.

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();
}
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
Hammer
  • 15
  • 6
  • 6
    Do you just need all of the text? If so, see [File.ReadAllText](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readalltext?view=netframework-4.8). Check out [File.ReadAllLines](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readalllines?view=netframework-4.8) too. Both have async variants. – Broots Waymb Apr 23 '19 at 14:03
  • yes i need reed all text with File.ReadAllText is fit for me. – Hammer Apr 23 '19 at 14:37

1 Answers1

1

Please see the 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);
}
IronAces
  • 1,857
  • 1
  • 27
  • 36
Bart van der Drift
  • 1,287
  • 12
  • 30