简体   繁体   中英

Relative Paths in ASP.Net

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.

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();
    }
}

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?

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();

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