文件上传控件获取文件名

时间:2014-11-30 09:59:02

标签: c# asp.net

以下两行有什么区别?他们做同样的事情,所以有什么不同吗?

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

2 个答案:

答案 0 :(得分:0)

第一个从给定路径返回文件名。第二个返回完整路径名,包括目录路径

来自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 ''

答案 1 :(得分:0)

第一个从路径获取文件名,但第二个将通过上传控件PostedFile属性直接提供上传的文件名,其属性包含有关上传文件的信息,如名称,大小和扩展名。

我建议使用第二个,不需要System.IO,因为控件具有返回文件名的属性。