Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File.WriteAllText and File.Copy issue

Tags:

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);
like image 735
nav100 Avatar asked Feb 04 '10 16:02

nav100


People also ask

What is file WriteAllText?

WriteAllText(String, String) is an inbuilt File class method that is used to create a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.

Does file WriteAllText create file?

WriteAllText(String, String, Encoding) Creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten.

How do I copy a file using another process?

To create a copy of a file that is read- and/or write-locked by another process on Windows, the simplest (and probably only) solution is to use the Volume Shadow Copy Service (VSS). The Volume Shadow Copy Service is complex and difficult to call from managed code.

How do you overwrite a text file in C#?

Use the File. WriteAllText method. It creates the file if it doesn't exist and overwrites it if it exists.


1 Answers

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.

like image 195
Hans Passant Avatar answered Sep 26 '22 14:09

Hans Passant