4

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

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

And I am getting this exception:

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

The folder Experiment is the folder of my web application.

Keren Caelen
  • 1,466
  • 3
  • 17
  • 38
user2992015
  • 53
  • 1
  • 4
  • 1
    When you use a relative path in ASP.NET, it uses the working directory which is not your web root, it's where your IIS is running. – Tobberoth Nov 14 '13 at 12:40

2 Answers2

8

You need to give physical path instead of relative path, use Server.MapPath("~") to get the root path of your site and then append the path of file 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");
}
Community
  • 1
  • 1
Adil
  • 146,340
  • 25
  • 209
  • 204
0

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");
}
Vinay Rajput
  • 362
  • 1
  • 4
  • 13