Here is my code,how do i use the length property to show length of the random.bin file?

static void Main(string[] args)
        {

            FileStream fs = new FileStream("random.bin", FileMode.OpenOrCreate, FileAccess.ReadWrite);
            // has to be declared in method scope
            Random r = new Random();
            for (int i = 0; i < 10; i++)
            {
                int num = r.Next();
                byte[] byteArr = BitConverter.GetBytes(num);
                fs.Write(byteArr, 0, byteArr.Length);
                Console.WriteLine(num);
            }

            FileInfo info1 = new FileInfo("random.bin");

            string fullName = info1.FullName;
            Console.WriteLine("Full name {0}",fullName);

            DateTime time = info1.CreationTime;
            Console.WriteLine("Creation time {0}",time);

            time = info1.LastAccessTime;
            Console.WriteLine("LastAccessTime {0}",time);

            time = info1.LastWriteTime;
            Console.WriteLine("LastWriteTime {0}",time);




            Console.ReadKey();  

        }

i have tried this:

FileInfo info = new FileInfo(@"random.bin");
            long value = info.Length;
            Console.WriteLine("The length is {0}",value);

but it does'n work,returns 0 bytes,but actual file is 40 bytes

Recommended Answers

All 2 Replies

The FileStream hasn't closed the file yet. Therefore the length hasn't been determined. Try wrapping the Filestream block in a using block. This will automaitcally close the stream and the length can then be determined:

using (FileStream fs = new FileStream("random.bin", FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
    // has to be declared in method scope
    Random r = new Random();
    for (int i = 0; i < 10; i++)
    {
        int num = r.Next();
        byte[] byteArr = BitConverter.GetBytes(num);
        fs.Write(byteArr, 0, byteArr.Length);
        Console.WriteLine(num);
    }
}
commented: Great help to my logic,many thanks +2

Please remember to mark the post solved if your question is answered Thank You

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.