如何在C#中检查文件是否为空?
我需要这样的东西:
if (file is empty)
{
// do stuff
}
else
{
// do other stuff
}
Run Code Online (Sandbox Code Playgroud)
tan*_*ius 103
if( new FileInfo( "file" ).Length == 0 )
{
// empty
}
Run Code Online (Sandbox Code Playgroud)
检查Exists属性以查找文件是否存在.
TDa*_*Dao 13
FileInfo.Length并非在所有情况下都有效,尤其是对于文本文件。如果你有一个文本文件,它曾经有一些内容,现在被清除了,长度可能仍然不是 0,因为字节顺序标记可能仍然保留。
您可以通过创建一个文本文件、向其中添加一些 Unicode 文本、保存它,然后清除文本并再次保存该文件来重现该问题。
现在FileInfo.Length将显示不为零的大小。
对此的解决方案是检查 Length < 6,基于字节顺序标记可能的最大大小。如果您的文件可以包含单个字节或几个字节,则在 Length < 6 时读取文件并检查读取大小 == 0。
public static bool IsTextFileEmpty(string fileName)
{
var info = new FileInfo(fileName);
if (info.Length == 0)
return true;
// only if your use case can involve files with 1 or a few bytes of content.
if (info.Length < 6)
{
var content = File.ReadAllText(fileName);
return content.Length == 0;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
Joe*_*orn 10
这里的问题是文件系统是易失性的.考虑:
if (new FileInfo(name).Length > 0)
{ //another process or the user changes or even deletes the file right here
// More code that assumes and existing, empty file
}
else
{
}
Run Code Online (Sandbox Code Playgroud)
这可以而且确实发生了. 通常,处理file-io场景所需的方法是重新考虑使用异常块的过程,然后将开发时间用于编写良好的异常处理程序.
if (!File.Exists(FILE_NAME))
{
Console.WriteLine("{0} does not exist.", FILE_NAME);
return;
}
if (new FileInfo(FILE_NAME).Length == 0)
{
Console.WriteLine("{0} is empty", FILE_NAME);
return;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
69371 次 |
| 最近记录: |