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);
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.
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.
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.
Use the File. WriteAllText method. It creates the file if it doesn't exist and overwrites it if it exists.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With