6

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.

How should I do this?

HelpNeeder
  • 6,383
  • 24
  • 91
  • 155

2 Answers2

13

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

AaA
  • 3,600
  • 8
  • 61
  • 86
10

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

Community
  • 1
  • 1
Jon
  • 428,835
  • 81
  • 738
  • 806
  • The answer in the link is in the question more than the answers, as you want the logical size of the file contents. – amalgamate Sep 06 '13 at 16:35
  • my .log file has lenght larger than 0, even if it is empty, so this doesn't work everytime – Qerts Apr 18 '15 at 07:58