Reputation: 58
I am trying to design a web form in ASP.NET using Visual Studio Express 2012.
I need to take data from some text boxes
, and write it to a Text file
.
This is a very simple program, but I am having trouble setting the file path.
This application will be sent to someone else, and they have to run the project from their computer.
The file I want is called Database.txt
and it is found in D:\Project\bin\Database.txt
.
So if he pastes this folder in his Desktop, it becomes C:\Users\Desktop\Project\bin\Database.txt
.
I am having trouble setting a dynamic path that can find this file regardless of where the project folder is.
Upvotes: 1
Views: 844
Reputation: 923
use Server.MapPath("/") to get physica path of ur virtual directory
see this. post for server.mappath Server.MapPath("."), Server.MapPath("~"), Server.MapPath(@"\"), Server.MapPath("/"). What is the difference?
Upvotes: 1
Reputation: 2530
Use this code:
public void WriteToFile(String text)
{
string logFileName = Server.MapPath("~/bin/DataBase.txt");
using (StreamWriter writer = File.AppendText(logFileName))
{
writer.WriteLine(text);
writer.Flush();
writer.Close();
}
}
Upvotes: 2
Reputation: 17614
What you can do is put the path in web.config
file and set the values as per requirement.
Here is some sample code that should help you
This goes into your web.config.
<configuration>
<appSettings>
<add key="myFilePath" value="C:\\whatever\\Data\\"/>
</appSettings>
</configuration>
And this is how you read it:
path = System.Web.Configuration.WebConfigurationManager.AppSettings["myFilePath"].ToString();
Upvotes: 0