Yuki Kutsuya
Yuki Kutsuya

Reputation: 4088

Filestream gives an error with spaces

I am trying to read a file (which works perfectly), the only problem is that when there is a space in the path, the code crashes and tells me there is no such path. Does anyone know how to escape these spaces or another solution? Thanks!

Here is the code I have:

public static string ReadValue(string value)
        {
            try
            {
                FileStream propertiesFile = new FileStream(ServerLocation + FileName, FileMode.Open);
                StreamReader sr = new StreamReader(propertiesFile);
                string Line = sr.ReadLine();
                while (Line != null)
                {
                    if (Line.Contains(value))
                    {
                        var setting = Line.Split('=')[1];
                        Console.WriteLine(setting);
                        sr.Close();
                        return setting;
                    }
                    Line = sr.ReadLine();
                }
                sr.Close();
            }
            catch (IOException e)
            {
                Console.WriteLine("Cannot find the specified file.");
                Console.WriteLine(e.ToString());
                return null;
            }
            return null;
        }

Upvotes: 0

Views: 2559

Answers (1)

Tommaso Belluzzo
Tommaso Belluzzo

Reputation: 23675

Normally, a path with whitespaces should not pose problems "C:\My Directory\Files" should be absolytely ok... maybe you are forgetting slashes somewhere in the begin of ServerLocation or at the end of FileName.

String path = Path.Combine(ServerLocation, FileName);

Or:

FileStream propertiesFile = new FileStream(ServerLocation.Trim() + FileName.Trim(), FileMode.Open);

Also, as suggested in my comment, change your loop to:

while ((Line = sr.ReadLine()) != null)
{
    if (Line.Contains(value))
    {
        var setting = Line.Split('=')[1];
        Console.WriteLine(setting);
        sr.Close();
        return setting;
    }
}

Upvotes: 2

Related Questions