streamwriter写入html,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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值