我在更改文件夹位置时出错

时间:2014-11-25 21:09:41

标签: c# string linq substring

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

错误:

  

enter image description here

代码段:

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;
    }

1 个答案:

答案 0 :(得分:1)

我假设您使用的路径中的文件名不超过8个字符,因此对子串(0,8)的调用失败。

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

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

然后按照Substring(0, charactersToRead)

的方式更改方法调用