Question

I am trying to save some data to a file, but the files are saved to an incorrect directory.

using (StreamWriter sw = new StreamWriter(dir + "\\temp" + x + ".txt"))
    sw.Write(data);

On Windows, this works fine. However, when I run this on Linux (Ubuntu, but I don't think that matters), under Mono, my files get saved with the backslashes in the name.

I have tried using Path.Combine(dir, "temp" + x + ".txt"); and forward slashes. Didn't work.

Anyone has any suggestions?

EDIT: Turns out that my "trying" of the above mentioned solutions was not very good. I was so used to Visual Studio recompiling every time I ran the application that I forgot to check whether MonoDevelop actually did the same.

After making changes and rebuilding I have found that all three solutions provided in the answers work.

Était-ce utile?

La solution

Use Path.DirectorySeparatorChar instead of hard coding \. This will expand out to the correct slash on the appropriate platform.

Autres conseils

NET Framework gives you a lot of tools to deal with paths. Starting from the Path class

using (StreamWriter sw = new StreamWriter(Path.Combine(dir, "temp", x + ".txt"))
    sw.Write(data);

No slash or backslash

SIDE NOTE: The Path.Combine method that accepts 3 strings arguments to combine in a valid path for the current operating system is available from NET.4.0 onward

Don't use backslash at all, use a forward slash instead. Works on Unix and all versions of DOS and Windows -- yes even back to DOS 2.0

ADDED

Create all of the intermediate directories first before creating the file.

ADDED PEDANTIC RANT

While Path.Combine is frequently useful, I mostly hard-code slash instead for convenience when I am using path strings directly in text strings because the code is easier to read (1 character vs. many) and it always works. I suppose in theory, .Net could be ported to something that does not accept slash as a path seperator, but the amount of breakage would be so severe, I would expect the .Net framework on that platform would translate the path separator internally.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top