C# System.IO.DirectoryNotFoundException: Could not find a part of the path

             string directory = @"D:/user/user.txt";
             FileStream FS = new FileStream(directory, FileMode.Append);
             StreamWriter SW = new StreamWriter(FS);
             string register;
             register = $"{generateID()};{txtfirstName.Text};{txtLastName.Text};{txtUser.Text};{txtEmail.Text};{txtPersonalID.Text}";
        catch (Exception ex)

I run this code in c# windows forms .NET framework and constanly i get the same message. I am in university and i am pretty new in programming so i have no idea what could be wrong. What are your thoughs? Any idea?

enter image description here

>Solution :

Your question is a little confusing. First of all, you shouldn’t name your variable directory because in the end it is a file name and used as such.

(I’ll ignore the difference between the image "D:\user\user.txt" and the code "D.:\user\user.txt" and will assume you actually ment and did use the first).

Most likely, the D:\User directory does not exist and the FileStream class will not create it for you. It will simply assume that all (sub) directories up to the specified file name exist and fail otherwise.

So make sure that the directory exists, either outside your application, or like so:

string fileName = @"D:\user\user.txt";
string directory = Path.GetDirectoryName(fileName);
if (!Directory.Exists(directory))
FileStream FS = new FileStream(fileName, FileMode.Append);

// ... rest of code

Leave a Reply