简体   繁体   中英

C# Save File at Location of Your App

I am trying to save to a file like this:

    string path = AppDomain.CurrentDomain.BaseDirectory;
    fs = new System.IO.FileStream(path, System.IO.FileMode.Append, System.IO.FileAccess.Write);

but I am getting DirectoryNotFoundException although directory exists.

Here is the method

public static void WriteToFile(string s)
{
    string path = AppDomain.CurrentDomain.BaseDirectory;
    fs = new System.IO.FileStream(path, System.IO.FileMode.Append, System.IO.FileAccess.Write);
    sw = new System.IO.StreamWriter(fs);
    sw.WriteLine(s);
    sw.Flush();
    sw.Close();
    fs.Close();
}

I am not sure why is this happening. Thanks

You need to specify a File Name , the Directory alone in not enough to create a file:

public static void WriteToFile(string s, string fileName)
{
    string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName);
    fs = new System.IO.FileStream(path, System.IO.FileMode.Append, System.IO.FileAccess.Write);
    sw = new System.IO.StreamWriter(fs);
    sw.WriteLine(s);
    sw.Flush();
    sw.Close();
    fs.Close();
}

Usage:

WriteToFile("Some Text To Write", "SampleFileName.txt");

Here is the documentation of:

public FileStream(string path, FileMode mode, FileAccess access);

Parameters: path: A relative or absolute path for the file that the current FileStream object will encapsulate.

Your' path is a directory, but System.IO.FileStream.FileStream(string path, FileMode mode, FileAccess access) expects a file path, so i modify your code like below:

public static void WriteToFile(string s)
    {
        string path = AppDomain.CurrentDomain.BaseDirectory + "a.txt";
        var fs = new System.IO.FileStream(path, System.IO.FileMode.Append, System.IO.FileAccess.Write);
        var sw = new System.IO.StreamWriter(fs);
        sw.WriteLine(s);
        sw.Flush();
        sw.Close();
        fs.Close();
        Console.WriteLine(path);
        Console.ReadKey();
    }

output: d:\\users\\zwguo\\documents\\visual studio 2013\\Projects\\ConsoleApplication15\\Consol eApplication15\\bin\\Debug\\a.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM