Search code examples
c#filestreamresource-file

Open Resource File with FileStream fails


I want to open a Resource File with the FileStream Class. It's a text File and I want to read it Line by Line.

FileStream fs = new FileStream(Properties.Resources.Testing, FileMode.Open, FileAccess.Read);

The called Exception is System.ArgumentException and it says there is an invalid character.

I hope anyone can help me to fix this, or if theres a better way it's also ok but I need the File in the .exe so it needs to be a Resource..


Solution

  • When you add a text file as a resource, it will be embedded as a string. So your FileStream constructor call will assume that you are trying to open a file on disk with a name that is the same as the text file content. That ends poorly of course.

    It isn't very clear if you really want a stream, the string tends to be good as-is, you might consider the String.Split() method to break it up into lines. Or maybe you like the StringReader class so you can use ReadLine():

        using (var rdr = new StringReader(Properties.Resources.Testing)) {
            string line;
            while ((line = rdr.ReadLine()) != null) {
                // Do something with line
                //...
            }
        }