You may have encountered such a situation.
Run similar Code Streamreader SR = New Streamreader ( " Test.txt " );
The system prompts "cocould not find file 'C:" Windows "System32" test.txt ".
This is caused by incorrect paths.
Fortunately, there are many path-related attributes in the Asp.net request object.
applicationpath |
virtual root directory path of the Program |
currentexecutionfilepath |
virtual path of the current request |
filepath |
path |
pathinfo |
physicalapplicationpath |
physical path of the virtual root directory of the Program |
physicalpath |
physical path of the request URL |
rawurl |
original URL of the current request |
URL |
URL Information of the current request |
For example, if I have a website named aspnetc, It is a sub-directory c: \ webs under the root directory of my website.
The output is as follows:
Applicationpath :"/"
Currentexecutionfilepath:/aspnetc/testpath. aspx
Filepath:/aspnetc/testpath. aspx
Path:/aspnetc/testpath. aspx
Pathinfo:
Physicalapplicationpath: C: \ webs \
Physicalpath: C: \ webs \ aspnetc \ testpath. aspx
Rawurl:/aspnetc/testpath. aspx
Rawurl contains querystring information. pathinfo can be used for URL rewriting.
Very useful "~ "And page. resolveurl can be combined to easily obtain the path
"~ "Represents the root directory of the current application, which is often used in controls to locate images, CSS, and other files.
If the application is moved and placed under different root directories, the problem may occur.
The resolveurl of page is used to solve this problem.
If your program is in "/somedir"
Page. resolveurl ("~ /Images/image1.jpg ") Return"/somedir/images/image1.jpg"
In the root directory
Page. resolveurl ("~ /Images/image1.jpg ") will simply return"/images/image1.jpg"
Server. mappath Method
Server. mappath ("/") server. mappath ("~ ") Obtain the physical path of the root directory of the current application.
Server. mappath (".") to obtain the physical path of the current directory
Server. mappath ("..") to obtain the physical path of the parent directory
Use path. Combine to connect to the path//Returns C: "testdir" Images "image1.jpg
Path. Combine (@"C:"Testdir",@"Images"Image1.jpg");
Methods of the path class in. net
1. Path. Combine (string, string)
Returns a path based on the given two paths.
For example:
String completepath = system. Io. Path. Combine (@ "C: \ MyApp", @ "Images \ skyline.jpg ");
A full path c: \ MyApp \ images \ skyline.jpg will be returned.
The first parameter can end. 2. Path. getextension (string)
Returns the extension of the given file path. For example: String fileextention = system. Io. Path. getextention (@ "C: \ MyApp \ images \ skyline.jpg ");
Will return "jpg"
3. Path. getfilename (string)
Returns the full path of the file name (including the extension). For example, string filename = system. Io. Path. getfilename (@ "C: \ MyApp \ images \ skyline.jpg ");
"Skyline.jpg" is returned"