How to Read and Write a Binary File At the Same Time in C#?


You can read and write a binary file at the same time in almost any modern programming languages (as far as I know, not VBScript). If you open the file in the right mode, then you can just move the stream pos around. Luckly, in C#, you could use the FileAccess.ReadWrite constant attribute when you open a File using FileStream class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
static void Main(string[] args)
{
    var tmpfile = Path.GetTempFileName();
    try
    {                
        using (var fs = new FileStream(tmpfile, FileMode.Open, FileAccess.ReadWrite))
        {
            var randNum = new Random();
 
            const int numOfBytes = 100;
 
            // Generate Random Data to Write
            var dataToWrite = Enumerable
                .Repeat(0, numOfBytes)
                .Select(i => (byte)randNum.Next(0, 255))
                .ToArray();
 
            fs.Write(dataToWrite, 0, dataToWrite.Length);
 
            // Rewind to the Top and Read them In
            var dataToRead = new byte[numOfBytes];
            fs.Seek(0, SeekOrigin.Begin);
            fs.Read(dataToRead, 0, dataToRead.Length);
 
            // Verification
            for (var i = 0; i < numOfBytes; ++ i)
            {
                if (dataToRead[i] != dataToWrite[i])
                {
                    throw new Exception("Bad things happen!");
                }
            }
        }
    }
    finally
    {
        File.Delete(tmpfile);
    }
}
static void Main(string[] args)
{
    var tmpfile = Path.GetTempFileName();
    try
    {                
        using (var fs = new FileStream(tmpfile, FileMode.Open, FileAccess.ReadWrite))
        {
            var randNum = new Random();

            const int numOfBytes = 100;

            // Generate Random Data to Write
            var dataToWrite = Enumerable
                .Repeat(0, numOfBytes)
                .Select(i => (byte)randNum.Next(0, 255))
                .ToArray();

            fs.Write(dataToWrite, 0, dataToWrite.Length);

            // Rewind to the Top and Read them In
            var dataToRead = new byte[numOfBytes];
            fs.Seek(0, SeekOrigin.Begin);
            fs.Read(dataToRead, 0, dataToRead.Length);

            // Verification
            for (var i = 0; i < numOfBytes; ++ i)
            {
                if (dataToRead[i] != dataToWrite[i])
                {
                    throw new Exception("Bad things happen!");
                }
            }
        }
    }
    finally
    {
        File.Delete(tmpfile);
    }
}

The above example creates a temporarily file, writes some random data (via LINQ) to it, rewinds the file pointer to the begining (using Seek method), reads the data into another array, and finally verifies the content, to see if they match. Exceptions are thrown if there is a mismatch, which may indicate that the hard disk is corrupted.

It may seem useless code. However, this is the CORE idea of the USB-check software:

write some data, and read them in to see if they match! Click To Tweet

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
335 words
Last Post: Throw Often, Catch Rarely
Next Post: How to Get the GUID using VBScript or Javascript (JScript) using Scriptlet.TypeLib?

The Permanent URL is: How to Read and Write a Binary File At the Same Time in C#?

Leave a Reply