Could not find path in web application

I am trying to write to a text file with using the ASP.NET 4.5 with c#following code:

using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"./Experiment/main.txt", true))
{
file.WriteLine(DateTime.UtcNow.ToString() + " test");
}

And I get this exception:

"Could not find a part of the path 'C:\Windows\SysWOW64\inetsrv\Experiment\main.txt'."

Folder Experimentis the folder of my web application.

+4
source share
2 answers

You need to specify the physical path instead of the relative path, use Server.MapPath("~")to get the root path of your site, and then add the path to it. You can learn more about Server.MapPath in this post.

using (System.IO.StreamWriter file = new System.IO.StreamWriter(Server.MapPath(@"~/Experiment/main.txt"), true))
{
     file.WriteLine(DateTime.UtcNow.ToString() + " test");
}
+7
source

Try this code

using (System.IO.StreamWriter file = new System.IO.StreamWriter(AppDomain.CurrentDomain.BaseDirectory+"Experiment/main.txt", true))
{
         DirectoryInfo dirInfo = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory+"Experiment/main.txt");
            if (!dirInfo.Exists)
            {
                dirInfo.Create();
            }
     file.WriteLine(DateTime.UtcNow.ToString() + " test");
}
0
source

All Articles