NET问答: 有最干净利落的读写文件方式吗?

咨询区

  • ApprenticeHacker

在 C# 中有很多种读写文件的方式 (文本文件,非二进制)。

为了践行 do more, write less 的思想,现寻找一种最简单最少代码量的方式,因为在我的项目中有太多的功能需要读写文件了。

回答区

  • vc 74

可以使用 C# 中的 File.ReadAllTextFile.WriteAllText

MSDN 上提供了如下的例子。


// 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);


  • Roland

可以通过 扩展方法 的方式实现最少代码的写法,我敢打赌绝对是最简单的,做法就是在 string 上做扩展,具体用什么名字就取决于个人喜好了。


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

有了扩展方法后,用起来就非常简单了。


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

看起来是不是非常美好,所以我决定分享给你们啦,祝使用愉快。

点评区

小编在学习C#的早期,都是通过 StreamWriterStreamReader 来操控文件,参考代码如下:


        static void Main(string[] args)
        {
            using (StreamWriter writetext = new StreamWriter("write.txt"))
            {
                writetext.WriteLine("writing in text file");
            }

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

后来莫名其妙的知道了 File 下居然还有 Read 和 Write 系列静态扩展方法后,再也回不去了。。。????????????

不过奇怪也没啥奇怪的,底层大多还是 StreamWriterStreamReader 的封装而已,如下图所示:

原文链接:https://stackoverflow.com/questions/7569904/easiest-way-to-read-from-and-write-to-files

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值