为什么在调用Path.GetFileName()

时间:2019-06-19 04:56:39

标签: c# asp.net-mvc

在我的方法中,我提供文件夹名称并逐个获取文件。 它提供了完整的文件路径,如image所示,并提供了带有双斜杠(//)的路径。

这是我的代码:

    public void DeleteFunction(string FolderName)
        {
           var folderpath = AppDomain.CurrentDomain.BaseDirectory+FolderName;
           var filescount = Directory.GetFiles(folderpath, "*", SearchOption.AllDirectories).Length;
           string[] files = Directory.GetFiles(folderpath );
           List<string> filenames = null;
           for(int i=0;i<filescount;i++)
           {
               filenames[i] = Path.GetFileName(files[i]);            
           }
        }

现在我只想获取文件名而不是完整路径,所以我使用了Path.GetFileName()但它引发了错误

2 个答案:

答案 0 :(得分:2)

有两个错误。首先,您需要初始化List<string> filenames = new List<string>();。在for内,您必须像Add一样使用filenames.Add(Path.GetFileName(files[i]));,否则将得到此异常System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.

public void DeleteFunction(string FolderName)
{
    var folderpath = AppDomain.CurrentDomain.BaseDirectory + FolderName;
    var filescount = Directory.GetFiles(folderpath, "*", SearchOption.AllDirectories).Length;
    string[] files = Directory.GetFiles(folderpath);
    List<string> filenames = new List<string>();
    for (int i = 0; i < filescount; i++)
    {
        filenames.Add(Path.GetFileName(files[i]));
    }
}

更多信息,您可以使用Linq并最小化代码,如下所示。导入名称空间using System.Linq;

public void DeleteFunction(string FolderName)
{
    string[] files = Directory.GetFiles(GetTempSavePath(clientId), "*", SearchOption.AllDirectories);
    List<string> filenames = files.Select(file => Path.GetFileName(file)).ToList();
}

答案 1 :(得分:1)

由于没有实例化List<string>,所以收到此错误。创建List实例,您将不会遇到问题,将文件名添加到适当的列表变量,即filenames

类似

public void DeleteFunction(string FolderName)
    {
        var folderpath = AppDomain.CurrentDomain.BaseDirectory+FolderName;
       var filescount= Directory.GetFiles(folderpath, "*", SearchOption.AllDirectories).Length;
       string[] files = Directory.GetFiles(folderpath );
       List<string> filenames = new List<string>();
                              // ^^^^^^^^^^^^^^^^ this was missing in your code 
       for(int i=0;i<filescount;i++)
       {

           filenames.Add(Path.GetFileName(files[i]));
         // ^^^^^^^^^^^^^^^^ You were missing .Add() function to insert file name to list
       }
    }