Reading a text File

Category: c# language

Question

NewCoder61 on Sun, 22 Jul 2012 03:25:12


            if (File.Exists("C:\\text.txt"))
            {
                FileStream Fs = new FileStream("C:\\text.txt", FileMode.Open, FileAccess.Read);                
                byte[] MyByte=new byte[1024];               
                Fs.Read(MyByte, 0, 1024);
                Console.WriteLine(Encoding.ASCII.GetString(MyByte));
             
            }
            else
            {

                FileStream Fs = new FileStream("C:\\text.txt", FileMode.CreateNew, FileAccess.Write);
                byte[] MyByte = null;
                MyByte=Encoding.ASCII.GetBytes("Hello!");
                Fs.Write(MyByte, 0, MyByte.Length);

            }

For reading my text from the file how can I set the byte array to the real size of my file instead of 1024?

Thanks


Replies

JohnWein on Sun, 22 Jul 2012 05:08:06


This can't be what you want, but it's what you ask:  replace 1024 with FS.Length cast to an int.