Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read file stream reader

Tags:

c#

filestream

What is my mistake as I'm unable to find an example on the Internet that matches what I'm doing or at least I'm not sure if it does?

The problem I'm having is it does not like

hexIn = fileStream.Read()

Code:

FileStream fileStream = new FileStream(fileDirectory, FileMode.Open, FileAccess.Read);
String s;

try
{
    for (int i = 0; (hexIn = fileStream.Read() != -1; i++)
    {
        s = hexIn.ToString("X2");
        //The rest of the code
    }
}
finally
{
    fileStream.Close();
}
like image 381
Simon Avatar asked Jan 20 '23 17:01

Simon


2 Answers

Missing ")". . Try:

using (StreamReader sr = new StreamReader("TestFile.txt"))
{
    String line;

    while ((line = sr.ReadLine()) != null)
    {
        s=...
    }
}
like image 189
soandos Avatar answered Jan 31 '23 07:01

soandos


There are a few things I would do differently.

The first, is you should using FileStream with a using. But actually, if you're just trying to read the lines in a text file, a StreamReader would be ok:

try
{
    using (StreamReader sr = new StreamReader("TestFile.txt"))
    {
        String line;

        while ((line = sr.ReadLine()) != null)
        {
            // convert line to Hex and then format with .ToString("X2")
        }
    }
}
catch
{
    // handle error
}

If you're trying to convert your entire input file to a hex value, let us know. I'll just assume line-by-line for now.

like image 34
Cᴏʀʏ Avatar answered Jan 31 '23 09:01

Cᴏʀʏ