Search code examples
c#arraysresourcesstreamwriter

C# Cannot use Streamwriter on a txt file in C# Properties.Resources


I am currently working on an assignment for school where I am trying to write a 2D string array into a text file. I have the array and know its working fine however every time I try to read the file into Streamwriter I get "System.ArgumentException: 'Illegal characters in path.'". I am relatively new to C# and I have no idea how to fix this.

This is my code. I just need to know how to write my 2D array into the text file without getting this error. Thanks, all and any help is much appreciated!

    // This line under is where the error happens
    using (var sw = new StreamWriter(Harvey_Norman.Properties.Resources.InventoryList))
        {
            for (int i = 0; i < 4; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    sw.Write(InventoryArray[i, j] + " ");
                }
                sw.Write("\n");
            }

            sw.Flush();
            sw.Close();
        }

Solution

  • My guess is that Harvey_Norman.Properties.Resources.InventoryList is a resource in your project that is typed as a string-- and the value of that string is not a valid path for your operating system.

    StreamWriter will either take a string, in which case it expects to open a file with the path of that string; or it will take a stream, and you can write to that stream. It looks like you are trying to do the former; but you need to check the value of that resource to see if it is a vaild path.