简体   繁体   中英

File upload control get file name

What is the difference between the 2 lines below? They do the same thing so is there any difference ?

string filename = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
string filename = FileUpload1.PostedFile.FileName;

First one returns the file name from a given path. Second one returns the full path name including directory path

From MSDN - GetFileName :

string fileName = @"C:\mydir\myfile.ext";
string path = @"C:\mydir\";
string result;

result = Path.GetFileName(fileName);
Console.WriteLine("GetFileName('{0}') returns '{1}'", 
    fileName, result);

result = Path.GetFileName(path);
Console.WriteLine("GetFileName('{0}') returns '{1}'", 
    path, result);

// This code produces output similar to the following: 
// 
// GetFileName('C:\mydir\myfile.ext') returns 'myfile.ext' 
// GetFileName('C:\mydir\') returns ''

The first one gets filename from the path, but second one will directly give the uploaded filename via upload control PostedFile property whose properties have information about uploaded file like name,size and extension .

I suggest to use second one, no need of System.IO as control has property which returns filename.

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