user36322
user36322

Reputation: 241

c# writing to a file without full path

If I use this code

File.AppendAllText("C:/Users/Michael/Documents/Visual Studio 2010/Projects/PuzzleGame/PuzzleGame/PuzzleGameContent/player.TXT", "hi");

The file will save and add "hi" to the end of it. However, if I do something like this:

File.AppendAllText("player.TXT", "what is good?");

The file won't have a "what is good?" at the end of it. I can read files just fine using only the "player.TXT" filename but I can't write to a file using only that. Can anyone help me?

Upvotes: 5

Views: 6711

Answers (4)

AwokeKnowing
AwokeKnowing

Reputation: 8206

Your working directory is wherever the .exe is (unless you change it). So you see, when you compile, the exe ends up in the bin folder, so your player.txt would need to be there, not with your source.

edit: I bet you're appending to player.txt THEN you read it and that's why it worked fine, because you created a new one in your bin folder. Otherwise, read would not have worked. If you go in your bin folder and delete player.txt, your readfile shouldn't work.

Upvotes: 8

outlawpoet
outlawpoet

Reputation: 1

The problem is that AppendAllText is a method which will create the file if it doesn't already exist. So when you use an incomplete path it is unsure whether to create a new file in a base directory or add to an already existing file. If you can't use the full path for whatever reason, you could get the current working directory using something like:

File.AppendAllText(System.Environment.CurrentDirectory + "player.TXT", "what is good?");

So long as the current directory is correct, it'll work the same as your first working example.

Upvotes: 0

Jon Raynor
Jon Raynor

Reputation: 3892

Most likely there are two files on the file system, one in the directory that is explicitly defined in the first example and one where the executable is running in the second example since no explicit path was defined in the parameter of the method call.

From MSDN:

Given a string and a file path, this method opens the specified file, appends the string to the end of the file, and then closes the file. The file handle is guaranteed to be closed by this method, even if exceptions are raised.

The method creates the file if it doesn’t exist, but it doesn't create new directories. Therefore, the value of the path parameter must contain existing directories

.

Upvotes: 2

Jonathan Wood
Jonathan Wood

Reputation: 67195

Both forms are perfectly valid. The likely scenario is that your second version is simply writing to a file at a different location, because not specifying the path will default to the current directory.

If you don't include a path, you'll want to ensure the current directory is valid for accessing the file.

Upvotes: 3

Related Questions