With Server.MapPath ("relative path").
Relative paths can be taken directly from different situations:
Take the Test.txt file in the current directory
String path = "Test.txt";
Take the Test.txt file under sub directory A in the current directory
String path = "A/test.txt";
Take the Test.txt file under peer A of the current directory
String path = ".. /a/test.txt ";
Take the Test.txt file under subdirectory A in the root directory of the site
String path = "~/a/test.txt";
If you want to take an absolute path:
Server.MapPath (relative path);
This method returns the absolute path of the passed relative path.
Then we use this absolute path to save the file;
Here is an example of uploading a file
First Import namespaces:
Using System.IO;
If there is a FileUpload control FileUpload1 on the page; and a Button1
We wrote this in the Button1 click event:
private void Button1_Click(Object sender,EventArges e)
{
// 取得上传的文件对象
HttpPostedFile hpf = FileUpload1.PostedFile;
// 取得文件路径
string filePath = hpf.FileName;
// 从路径中取出文件名用来作为保存的文件名
string filePath = Path.GetFileName(filePath);
// 取得服务器站点根目录的绝对路径
string serverPath = Server.MapPath("~/");
// 保存文件
hpf.Save(serverPath + filePath);
}