nav100
nav100

Reputation: 1487

File.WriteAllText and File.Copy issue

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);

Upvotes: 5

Views: 2322

Answers (3)

Chris Dunaway
Chris Dunaway

Reputation: 11216

What folder are you writing to? Could this be a Vista/7 folder virtualization issue?

If you could show us the actual code you are using, it would be helpful.

Upvotes: 0

Hans Passant
Hans Passant

Reputation: 941635

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.

Upvotes: 7

Antony Koch
Antony Koch

Reputation: 2053

Are the method calls concurrent as per your example?

If so, you could call File.WriteAllText twice to circumvent the issue, though I don't know why it's occuring.

You could do a File.Exists check prior to the copy, or perhaps try a Thread.Sleep(100) and see it's a disk I/O type issue.

Upvotes: 0

Related Questions