从StreamWriter获取文件大小

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

鉴于上面的代码,可以从StreamWriter文件大小吗?

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

 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 

干得好! 只需使用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); 

如果您需要特定文件的属性,我认为您正在寻找的是FileInfo。

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

你能试试这段代码吗?

 var size = writer.BaseStream.Length; 

* writer是你的StreamWriter

不,不是从StreamWriter本身可以找到文件的大小。 您必须使用FileInfo的长度 。