从StreamWriter获取文件大小

12
using (var writer = File.CreateText(fullFilePath))
{
   file.Write(fileContent);
}

考虑到上面的代码,可以从 StreamWriter 中知道文件大小吗?


9
好的,它是空的。 - SLaks
抱歉,我也得到了以下内容。writer.Write(fileContent); - Moh Moh Oo
代码看起来过于简化了。你会在使用关闭后获得有关获取大小的答案,这是你想要的吗? - H H
如果可能的话,从StreamWriter类中返回已写入的文本。 - Moh Moh Oo
你无法从已关闭的写入器或流中获取大小。 - H H
5个回答

26

是的,您可以尝试以下方法

long length = writer.BaseStream.Length;//will give unexpected output if autoflush is false and write has been called just before

注意: writer.BaseStream.Length 属性可能会返回意外的结果,因为 StreamWriter 不会立即写入,而是会缓存。因此,如果要获得预期的输出,需要将 AutoFlush = true

writer.AutoFlush = true; or writer.Flush();
long length = writer.BaseStream.Length;//will give expected output

@Downvoter能否解释一下? - Sriram Sakthivel
1
设置写入后的自动刷新是可行的,但是有些愚蠢。应该在适当的时候直接调用 Flush() - H H

3
我认为如果您需要特定文件的属性,则需要使用FileInfo。
FileInfo info = new FileInfo(fullFilePath);
//Gets the size, in bytes, of the current file.
long size = info.Length;

1

这里有一个方法!只需使用System.IO命名空间中的FileInfo类 :)

using System.IO;

var fullFilePath = "C:\path\to\some\file.txt";
var fileInfo = new FileInfo(fullFilePath);

Console.WriteLine("The size of the file is: " + fileInfo.Length);

1
基本上是正确的,但最好在using(){}上下文中显示。 - H H
FileInfo没有实现IDisposable接口,因此无法在其上使用using语句。 - Bearcat9425
1
对于上面提到的人,建议在使用上下文中展示它。 - Bearcat9425
把这段代码放在 using(writer) 之外,且在它之后是有必要的。 - H H
@mohmohoo 在文件大小增加之前,您必须将数据实际写入文件系统。这就是IO。 - Maritim
显示剩余7条评论

0

你能试试这段代码吗?

var size = writer.BaseStream.Length;

*writer 是你的 StreamWriter


你没有考虑缓冲。 - H H

0

不,你不能从StreamWriter本身找到文件的大小。你必须使用FileInfo的Length


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接