Easiest way to read from and write to files

后端 未结 12 1735
[愿得一人]
[愿得一人] 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:22

    @AlexeiLevenkov pointed me at another "easiest way" namely the extension method. It takes just a little coding, then provides the absolute easiest way to read/write, plus it offers the flexibility to create variations according to your personal needs. Here is a complete example:

    This defines the extension method on the string type. Note that the only thing that really matters is the function argument with extra keyword this, that makes it refer to the object that the method is attached to. The class name does not matter; the class and method must be declared static.

    using System.IO;//File, Directory, Path
    
    namespace Lib
    {
        /// <summary>
        /// Handy string methods
        /// </summary>
        public static class Strings
        {
            /// <summary>
            /// Extension method to write the string Str to a file
            /// </summary>
            /// <param name="Str"></param>
            /// <param name="Filename"></param>
            public static void WriteToFile(this string Str, string Filename)
            {
                File.WriteAllText(Filename, Str);
                return;
            }
    
            // of course you could add other useful string methods...
        }//end class
    }//end ns
    

    This is how to use the string extension method, note that it refers automagically to the class Strings:

    using Lib;//(extension) method(s) for string
    namespace ConsoleApp_Sandbox
    {
        class Program
        {
            static void Main(string[] args)
            {
                "Hello World!".WriteToFile(@"c:\temp\helloworld.txt");
                return;
            }
    
        }//end class
    }//end ns
    

    I would never have found this myself, but it works great, so I wanted to share this. Have fun!

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

    These are the best and most commonly used methods for writing to and reading from files:

    using System.IO;
    
    File.AppendAllText(sFilePathAndName, sTextToWrite);//add text to existing file
    File.WriteAllText(sFilePathAndName, sTextToWrite);//will overwrite the text in the existing file. If the file doesn't exist, it will create it. 
    File.ReadAllText(sFilePathAndName);
    

    The old way, which I was taught in college was to use stream reader/stream writer, but the File I/O methods are less clunky and require fewer lines of code. You can type in "File." in your IDE (make sure you include the System.IO import statement) and see all the methods available. Below are example methods for reading/writing strings to/from text files (.txt.) using a Windows Forms App.

    Append text to an existing file:

    private void AppendTextToExistingFile_Click(object sender, EventArgs e)
    {
        string sTextToAppend = txtMainUserInput.Text;
        //first, check to make sure that the user entered something in the text box.
        if (sTextToAppend == "" || sTextToAppend == null)
        {MessageBox.Show("You did not enter any text. Please try again");}
        else
        {
            string sFilePathAndName = getFileNameFromUser();// opens the file dailog; user selects a file (.txt filter) and the method returns a path\filename.txt as string.
            if (sFilePathAndName == "" || sFilePathAndName == null)
            {
                //MessageBox.Show("You cancalled"); //DO NOTHING
            }
            else 
            {
                sTextToAppend = ("\r\n" + sTextToAppend);//create a new line for the new text
                File.AppendAllText(sFilePathAndName, sTextToAppend);
                string sFileNameOnly = sFilePathAndName.Substring(sFilePathAndName.LastIndexOf('\\') + 1);
                MessageBox.Show("Your new text has been appended to " + sFileNameOnly);
            }//end nested if/else
        }//end if/else
    
    }//end method AppendTextToExistingFile_Click
    

    Get file name from the user via file explorer/open file dialog (you will need this to select existing files).

    private string getFileNameFromUser()//returns file path\name
    {
        string sFileNameAndPath = "";
        OpenFileDialog fd = new OpenFileDialog();
        fd.Title = "Select file";
        fd.Filter = "TXT files|*.txt";
        fd.InitialDirectory = Environment.CurrentDirectory;
        if (fd.ShowDialog() == DialogResult.OK)
        {
            sFileNameAndPath = (fd.FileName.ToString());
        }
        return sFileNameAndPath;
    }//end method getFileNameFromUser
    

    Get text from an existing file:

    private void btnGetTextFromExistingFile_Click(object sender, EventArgs e)
    {
        string sFileNameAndPath = getFileNameFromUser();
        txtMainUserInput.Text = File.ReadAllText(sFileNameAndPath); //display the text
    }
    
    0 讨论(0)
  • 2020-11-22 08:24

    Or, if you are really about lines:

    System.IO.File also contains a static method WriteAllLines, so you could do:

    IList<string> myLines = new List<string>()
    {
        "line1",
        "line2",
        "line3",
    };
    
    File.WriteAllLines("./foo", myLines);
    
    0 讨论(0)
  • 2020-11-22 08:24

    It's good when reading to use the OpenFileDialog control to browse to any file you want to read. Find the code below:

    Don't forget to add the following using statement to read files: using System.IO;

    private void button1_Click(object sender, EventArgs e)
    {
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
             textBox1.Text = File.ReadAllText(openFileDialog1.FileName);  
        }
    }
    

    To write files you can use the method File.WriteAllText.

    0 讨论(0)
  • 2020-11-22 08:24
    private void Form1_Load(object sender, EventArgs e)
        {
            //Write a file
            string text = "The text inside the file.";
            System.IO.File.WriteAllText("file_name.txt", text);
    
            //Read a file
            string read = System.IO.File.ReadAllText("file_name.txt");
            MessageBox.Show(read); //Display text in the file
        }
    
    0 讨论(0)
  • 2020-11-22 08:27
    FileStream fs = new FileStream(txtSourcePath.Text,FileMode.Open, FileAccess.Read);
    using(StreamReader sr = new StreamReader(fs))
    {
       using (StreamWriter sw = new StreamWriter(Destination))
       {
                sw.writeline("Your text");
        }
    }
    
    0 讨论(0)
提交回复
热议问题