【发布时间】:2014-08-14 18:59:34
【问题描述】:
在下面包含的代码中,当使用以下语句时,我可以将字符串“全名”的内容写入指定目录中的文本文件:
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();
}
}
}
【问题讨论】:
-
你可以改用
File.WriteAllText.. -
那是因为你看文件的时间不对。 FileStream 尚未刷新其缓冲区。它没有任何理由这样做,您没有关闭文件。在这里使用 using 语句不是可选的。
-
欢迎您!当你不以关于你的经历或你的研究的陈述开头时,问题通常看起来更好。最好从您的实际问题(感叹号后的所有内容)开始,然后在最后包含您研究中的相关引述和指向您的来源的链接。
标签: c# filestream streamwriter