Getting the file size from StreamWriter [closed]

时光总嘲笑我的痴心妄想 提交于 2019-12-09 14:57:56

问题


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

Given the above code, can the file size be known from StreamWriter?


回答1:


Yes, you can, try the following

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

Note: writer.BaseStream.Length property can return unexpected results since StreamWriter doesn't write immediately. It caches so to get expected output you need AutoFlush = true

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



回答2:


I think what you are looking for if you need properties of a specific file is FileInfo.

FileInfo info = new FileInfo(fullFilePath);
//Gets the size, in bytes, of the current file.
long size = info.Length;



回答3:


Here you go! Just use the FileInfo class in the System.IO namespace :)

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



回答4:


Could you try this piece of code ?

var size = writer.BaseStream.Length;

*writer is your StreamWriter




回答5:


No, not from StreamWriter itself can you find out about the file's size. You have to use FileInfo's Length.



来源:https://stackoverflow.com/questions/18127502/getting-the-file-size-from-streamwriter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!