【问题标题】:Getting an error when i am changing my folder location更改文件夹位置时出现错误
【发布时间】:2026-01-15 09:25:01
【问题描述】:

当我将我的位置更改为我的网络位置时出现错误。它只发生在一个文件夹中。我的错误是index and length must refer to location with in sub-string

错误:

代码sn-p:

private void list()
 {
 List<string> stFileNames = new List<string>();
        stFileNames.AddRange(arrRelease);
        foreach (var r in arrDraft)
        {
            if (stFileNames.FindAll(m => Path.GetFileNameWithoutExtension(m).ToUpper().Substring(0, 8).Equals(Path.GetFileNameWithoutExtension(r).ToUpper().Substring(0, 8))).Count == 0)
       //getting error in the above line.. Only when i am giving to one particular location
        /which i need then that time i am getting this error.
                stFileNames.Add(r);
        }

        dt.Columns.Add("Drawing Number");
        dt.Columns.Add("Drawing Path");
        dt.Columns.Add("Draft Path");
        dt.Columns.Add("Release Path");
        dt.Columns.Add("Error");
        dt.Columns.Add("Archive");

        List<FileDetails> lst = new List<FileDetails>();
        //matching files according to the realse folder
        foreach (string f in stFileNames)
        {
            Finder finder = new Finder(Path.GetFileName(f).Substring(0, 8));
            string abc = Array.Find(arrDraft, finder.Match);
            string def = Array.Find(arrRelease, finder.Match);
            string cdf = Array.Find(arrDrawing, finder.Match);
            //matching file in the location Drawing
            string ghi = Array.Find(arrArchive, finder.Match);
            //matching file in the location Archieve
            dt.Rows.Add(Path.GetFileNameWithoutExtension(f), cdf, abc, def, String.Empty, ghi);
        }
        dataGridView1.DataSource = dt;
    }

【问题讨论】:

  • @alykins Path.GetFileNameWithoutExtension(m).ToUpper().Substring(0, 8).Equals(Path.GetFileNameWithoutExtension(r).ToUpper().Substring(0, 8))).Count == 0)
  • 您的文件名不是 8 个字符长并且会引发该错误。是的,对不起,史黛西,我在发布这个问题后在代码中看到了你的评论——现在看到了。
  • 打破该行,并查看该列表的成员 - 其中一个或多个将少于 8 个字符长。您也许可以将其修改为 ithoutExtension(m).Where(m.length &gt; 7).ToUpper() 之类的东西,但该语法不正确-我不知道是否正确;其他人可能更了解它
  • @alykins Error 1 'string' does not contain a definition for 'Where' and no extension method 'Where' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
  • 是的,我在这方面的语法很糟糕——我充其量使用 LINQ 很危险——这是值得研究的东西(我认为无论如何),这里有一些真正的 LINQ 查询编写器。您将不得不玩一会儿,然后可能会找人帮助解决问题。

标签: c# string linq substring


【解决方案1】:

我假设您使用的路径中的文件名少于 8 个字符,因此对 Substring (0,8) 的调用失败。

在调用 substring 之前,您需要检查文件名的长度。假设对于 8 个字符以下的文件名,您只需要整个文件名,您可以执行以下操作:

var charactersToRead = Path.GetFileNameWithoutExtension(m).length < 8 ? Path.GetFileNameWithoutExtension(m).length : 8

然后按照Substring(0, charactersToRead) 的方式更改您的方法调用

【讨论】:

  • 更有用的 IMO-+1