C# – File.WriteAllText and File.Copy issue

c

I am creating a file using File.WriteAllText and copying the same file to another directory using File.Copy method. But for some reason it doesn't create a file in the source directory but it does copy it to destination directory.

What could be the problem? Please let me know.

File.WriteAllText(sourceFilePath, Contents.ToString());
File.Copy(sourceFilePath, destFilePath);

Best Answer

Well, you know for a fact that the file actually did get created, otherwise File.Copy() throws an exception. And File.Copy() never deletes the source file, like File.Move() does.

The simplest explanation is that the file is just getting created in a folder that you didn't expect. Which is common if sourceFilePath is not an absolute path. This commonly happens when you've used OpenFileDialog with its RestoreDirectory property set to false. For example.

Avoid this by always using absolute paths. Environment.GetFolderPath() is your friend.