【问题标题】:How to check if file content is empty?如何检查文件内容是否为空?
【发布时间】:2012-01-10 03:35:11
【问题描述】:

我正在尝试检查文件中是否没有任何内容。

这是我检查/创建/写入文件的内容:

class LastUsed
    {
        private static string dir = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + @"\Folder\";
        private static string file = dir + @"\Settings.txt";
        private string text;

        public void CheckFileStatus()
        {
            if (!Directory.Exists(dir))
            {
                DirectoryInfo directory = Directory.CreateDirectory(dir);
            }
            if (!File.Exists(file))
            {
                using (FileStream fileStream = File.Create(file))
                {
                }
            }
        }

        private void SetFileText(string writeText)
        {
            using (StreamWriter streamWriter = new StreamWriter(file))
            {
                streamWriter.Write(writeText);
            }
        }

        private string GetFileText()
        {
            string readText;

            using (StreamReader streamReader = File.OpenText(file))
            {
                readText = streamReader.ReadLine();
            }

            return readText;
        }

        public string Text
        {
            set 
            {
                text = value;
                SetFileText(text);
            }
            get 
            {
                return GetFileText(); 
            }
        }

正如我们所见,我可以使用属性读取/写入文件。所以我尝试检查 Text 属性的 null 值,但它似乎不起作用。

我应该怎么做?

【问题讨论】:

  • @M.Babcock,我还没有真正想到这一点。但这似乎是一个不错的解决方案。

标签: c#


【解决方案1】:

这段代码应该这样做

if (new FileInfo(fileName).Length ==0){
  // file is empty
} else {
  // there is something in it
}

fileName 是您要查找其大小的文件路径

【讨论】:

    【解决方案2】:

    只需检查文件大小是否为零字节:Get size of file on disk

    【讨论】:

    • 链接中的答案比答案更多,因为您需要文件内容的逻辑大小。
    • 我的 .log 文件的长度大于 0,即使它是空的,所以这并不是每次都有效
    猜你喜欢
    • 2015-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-30
    相关资源
    最近更新 更多