问题
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