Frontear
Frontear

Reputation: 1261

DirectoryNotFoundException even when file does exist

This is the code:

string file = Path.Combine(Environment.CurrentDirectory, "test.txt");
if (!File.Exists(file)) {
    File.CreateText(file); // will throw always
}

using (var writer = new StreamWriter(file)) { // will throw always
    //...
}

This will throw a DirectoryNotFoundException if the file doesn't exist and if it attempts to create it, and if the file does exist, then it will throw DirectoryNotFoundException when trying to use StreamWriter. I don't believe this code is wrong, so I am at a loss at what is the problem.

Update

The value of file is /tmp/test.txt. Yes, it always is throwing, the exception is

System.IO.DirectoryNotFoundException: Could not find a part of the path '/tmp/test.txt'

Update

A reboot has fixed this. I have no idea why this was being caused, but it might've simply been an IDE issue.

Upvotes: 1

Views: 2200

Answers (1)

TheGeneral
TheGeneral

Reputation: 81473

You are opening a file with

File.CreateText(file);

File.CreateText(String) Method

Returns StreamWriter A StreamWriter that writes to the specified file using UTF-8 encoding.

Then you are not closing it. Then you are trying to access the open file by opening it again

using (var writer = new StreamWriter(file))

However, the exception you are getting is another problem again. When using StreamWriter

DirectoryNotFoundException The specified path is invalid (for example, it is on an unmapped drive).

All the above aside, what i suggest you do is

string file = Path.Combine(Environment.CurrentDirectory, "test.txt");
Console.WriteLine(file);

//FileMode.Create will create or overwwrite the file
using (var fs = new FileStream(file,FileMode.Create))
   using (var writer = new StreamWriter(fs))
   { 
   }

Then if you still have problems, go to that directory and check if the file is there, check the permissions on the directory and file and make sure you have the appropriate access.

In short your code is suspect and you need to fix it, secondly you need to be sure what file it is your opening, thirdly, you need to check the permissions for that file and or directory

Upvotes: 2

Related Questions