开发者

DirectoryNotFound Exception in C#

开发者 https://www.devze.com 2023-02-14 00:44 出处:网络
I\'m trying to save a file at path WindowsFormsApplication1\\WindowsFormsApplication1\\SaveFilebut the following code returning me a \"DirectoryNotFound\" Exception with the message :

I'm trying to save a file at path WindowsFormsApplication1\WindowsFormsApplication1\SaveFile but the following code returning me a "DirectoryNotFound" Exception with the message :

Could not find a part of the path 'D:\WindowsFormsApplication1\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\SaveFile\Hello.tx

String Path = @".\SaveFile\Hello.txt";
FileInfo info = new FileInfo(Path);
if (!info.Exists)
{
    using (StreamWriter writer = info.CreateText())
    {
        writer.WriteLine("HELLO");
    }
} 

Could anyone pleas开发者_如何学Ce tell me how should I save a file at my desirable folder with specifying complete path?


When you are running in the debugger, your default path is under bin\Debug. That's what "." means in your path.

Which folder do you want to save to? You'll need to specify the full path. Perhaps you'll want to pull the path from a config file. That way, the path will be able to change based on where your application is deployed.


As the error message tells you the file will be saved in the subdirectory SaveFile under bin/debug. Before you can save a file you have to create a directory with Directory.CreateDirectory("SaveFile"). It will not be automatically created.


You need to make sure the directory exists prior to creating the text file.

String Path = @".\SaveFile\Hello.txt";
FileInfo info = new FileInfo(Path);
if (!info.Exists)
{
    if (!info.Directory.Exists)
        info.Directory.Create();

    using (StreamWriter writer = info.CreateText())
    {
        writer.WriteLine("HELLO");
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消