C# 如何检查文件内容是否为空?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8798231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 04:29:40  来源:igfitidea点击:

How to check if file content is empty?

c#

提问by HelpNeeder

I am trying to check if file doesn't have anything in it.

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

This is what I have which checks/create/write to file:

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

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

As we can see I can read/write file by using properties. So I have tried to check the Text property for null value but it doesn't seem to work.

正如我们所看到的,我可以使用属性来读/写文件。所以我试图检查 Text 属性的空值,但它似乎不起作用。

How should I do this?

我该怎么做?

采纳答案by Jon

Simply check if the file's size is zero bytes: Get size of file on disk.

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

回答by AaA

This code should do it

这段代码应该可以

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

fileName is the file path that you want to look for its size

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