Easiest way to read from and write to files

后端 未结 12 1736
[愿得一人]
[愿得一人] 2020-11-22 08:04

There are a lot of different ways to read and write files (text files, not binary) in C#.

I just need something that is easy and uses the least amount of c

相关标签:
12条回答
  • 2020-11-22 08:34

    In addition to File.ReadAllText, File.ReadAllLines, and File.WriteAllText (and similar helpers from File class) shown in another answer you can use StreamWriter/StreamReader classes.

    Writing a text file:

    using(StreamWriter writetext = new StreamWriter("write.txt"))
    {
        writetext.WriteLine("writing in text file");
    }
    

    Reading a text file:

    using(StreamReader readtext = new StreamReader("readme.txt"))
    {
       string readText = readtext.ReadLine();
    }
    

    Notes:

    • You can use readtext.Dispose() instead of using, but it will not close file/reader/writer in case of exceptions
    • Be aware that relative path is relative to current working directory. You may want to use/construct absolute path.
    • Missing using/Close is very common reason of "why data is not written to file".
    0 讨论(0)
  • 2020-11-22 08:35
         class Program
        { 
             public static void Main()
            { 
                //To write in a txt file
                 File.WriteAllText("C:\\Users\\HP\\Desktop\\c#file.txt", "Hello and Welcome");
    
               //To Read from a txt file & print on console
                 string  copyTxt = File.ReadAllText("C:\\Users\\HP\\Desktop\\c#file.txt");
                 Console.Out.WriteLine("{0}",copyTxt);
            }      
        }
    
    0 讨论(0)
  • 2020-11-22 08:37

    The easiest way to read from a file and write to a file:

    //Read from a file
    string something = File.ReadAllText("C:\\Rfile.txt");
    
    //Write to a file
    using (StreamWriter writer = new StreamWriter("Wfile.txt"))
    {
        writer.WriteLine(something);
    }
    
    0 讨论(0)
  • 2020-11-22 08:42

    Use File.ReadAllText and File.WriteAllText.

    MSDN example excerpt:

    // Create a file to write to.
    string createText = "Hello and Welcome" + Environment.NewLine;
    File.WriteAllText(path, createText);
    
    ...
    
    // Open the file to read from.
    string readText = File.ReadAllText(path);
    
    0 讨论(0)
  • 2020-11-22 08:42
    using (var file = File.Create("pricequote.txt"))
    {
        ...........                        
    }
    
    using (var file = File.OpenRead("pricequote.txt"))
    {
        ..........
    }
    

    Simple, easy and also disposes/cleans up the object once you are done with it.

    0 讨论(0)
  • 2020-11-22 08:42

    You're looking for the File, StreamWriter, and StreamReader classes.

    0 讨论(0)
提交回复
热议问题