编程语言
首页 > 编程语言> > c# – 为什么FileStream不作为Streamwriter的参数写入文本文件?

c# – 为什么FileStream不作为Streamwriter的参数写入文本文件?

作者:互联网

在下面的代码中,当使用以下语句时,我能够将字符串’fullname’的内容写入指定目录中的文本文件:
System.IO.File.WriteAllText(path,fullname);
但是,如果我将字符串路径写入FileStream对象(指定了参数),然后将该FileStream对象作为参数传递给StreamWriter对象,则会创建该文件,但不会写入任何内容.

第一次尝试:注释掉System.IO.File.WriteAllText(path,fullname);并使用它上面的三条线.这将创建文件,但不会将任何内容写入文件.

第二次尝试:取消注释System.IO.File.WriteAllText(path,fullname);陈述并评论它上面的三行.这可以根据需要执行.

这是完整的代码块:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace FileInputOutput
{
    class Program
    {
        static void Main(string[] args)
        {
            // Use the Split() method of the String Class
            string fullname = " Robert Gordon Orr ";
            fullname = fullname.Trim();
            string[] splitNameArray = fullname.Split(' ');
            Console.WriteLine("First Name is: {0}", splitNameArray[0]);
            Console.WriteLine("Middle Name is: {0}", splitNameArray[1]);
            Console.WriteLine("Last Name is: {0}", splitNameArray[2]);
            Console.WriteLine("Full name is: {0}", fullname);
            string path = @"C:\Programming\C#\C# Practice Folder\Console Applications\FileInputOutput\textfile.txt";

            FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite);
            StreamWriter toFile = new StreamWriter(fs);
            toFile.Write(fullname);

            //System.IO.File.WriteAllText(path, fullname);`enter code here`

            Console.ReadLine();

        }
    }
}

解决方法:

正如其他人所说:必须在.NET中刷新流才能将它们写入磁盘.这可以手动完成,但我只需更改您的代码以在您的流上使用语句:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace FileInputOutput
{
    class Program
    {
        static void Main(string[] args)
        {
            // Use the Split() method of the String Class
            string fullname = " Robert Gordon Orr ";
            fullname = fullname.Trim();
            string[] splitNameArray = fullname.Split(' ');
            Console.WriteLine("First Name is: {0}", splitNameArray[0]);
            Console.WriteLine("Middle Name is: {0}", splitNameArray[1]);
            Console.WriteLine("Last Name is: {0}", splitNameArray[2]);
            Console.WriteLine("Full name is: {0}", fullname);
            string path = @"C:\textfile.txt";

            using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite))
            {
                using (StreamWriter toFile = new StreamWriter(fs))
                {
                    toFile.Write(fullname);
                }
            }
            //System.IO.File.WriteAllText(path, fullname);`enter code here`

            Console.ReadLine();

        }
    }
}

在流上调用Dispose()(如隐式使用)会导致在使用块结束时刷新和关闭流.

标签:c,filestream,streamwriter
来源: https://codeday.me/bug/20190717/1490825.html