Easiest way to read from and write to files

后端 未结 12 1740
[愿得一人]
[愿得一人] 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
    {
        /// 
        /// Handy string methods
        /// 
        public static class Strings
        {
            /// 
            /// Extension method to write the string Str to a file
            /// 
            /// 
            /// 
            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!

提交回复
热议问题