I have an asp.net website that writes some data to a TXT file using a relative path. It does so with this command:
string currentDirectory = "./";
string individualDeviceTxt = "myfile.txt";
System.IO.StreamWriter fileW3 = new System.IO.StreamWriter(currentDirectory + individualDeviceTxt);
The file writes successfully to the following path:
C:\Program Files (x86)\Common Files\microsoft shared\DevServer\10.0
however, later on, when I try to transmit this file to the user, the relative directory ./ is pointed at a different path. Here is the code:
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.Clear();
response.AddHeader("Content-Disposition", "attachment; filename=" + currentDirectory + individualDeviceTxt + ";");
response.TransmitFile(currentDirectory + individualDeviceTxt);
response.End();
it is trying to send the file FROM ‘C:\Users\user\documents\visual studio 2010\Projects\myproject\myfile.txt which is not correct (it doesn’t exist there.)
So it’s apparent that “./” is pointed to a different folder for my second code snippet, but I want to be pointed to the same “./” used in the first snippet. What do I need to do to make this happen? I want to continue using ./ as the directory for myfile.txt in both spots.
Getting a path can be tricky in asp.net.
Here are four different ways to get your current path most only two provide the same results. Put this below in server side code. I like using the AppDomain it seems the most reliable in finding where your .aspx pages are located.
The results I got were. Hope this helps.
Runtime Path C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\e333f875\41caca57\assembly\dl3\9d915b4e\ee11a5b0_20d4cd01\MvcTutorial.DLL
Using Root C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\10.0\
Appdomain C:\Users\Robert\documents\visual studio 2010\Projects\MvcTutorial\MvcTutorial
Environment C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\10.0