2015-09-17 4 views
1

Привет Я пытаюсь подстроить путь к файлу, прежде чем он войдет в словарь. Я попытался объявить начальную точку, но получил ошибку:Подстановка пути к файлу

StartIndex не может быть больше длины строки. Имя параметра: STARTINDEX

Это мой код

private Dictionary<string,int> CreateDictionary(log logInstance) 
     { 
      Dictionary<string, int> dictionary = new Dictionary<string, int>(); 
      for (int entryIdex = 0; entryIdex < logInstance.logentry.Count(); entryIdex++) 
      { 
       logLogentry entry = logInstance.logentry[entryIdex]; 
       for (int pathIdex = 0; pathIdex < entry.paths.Count(); pathIdex++) 
       { 
        logLogentryPath path = entry.paths[pathIdex]; 
        string filePath = path.Value; 
        filePath.Substring(63); 
        string cutPath = filePath; 
        if (dictionary.ContainsKey(cutPath)) 
        { 
         dictionary[cutPath]++; 
        } 
        else 
        { 
         dictionary.Add(cutPath, 1); 
        } 
       } 
      } 
      return dictionary; 
     } 

Любая помощь будет большим.

Я также попытался сделать

filePath.Substring(0, 63); 

и

filePath.Substring(63, length); 
+1

Вы не назначаете возвращаемую строку из 'filePath.Substring (63)' любой переменной, почему? Однако эта перегрузка дает вам часть 63-го символа, поэтому строка должна содержать не менее 63 символов. Что вы на самом деле хотите? –

+0

Строка длиной 81 символ –

+0

Можете ли вы ее отладить и проверить? Кажется, что ошибка указывает, что строка меньше 63 символов. Кроме того, я думаю, что это: 'filePath.Подстрока (63); string cutPath = filePath; 'необходимо заменить на' string curPath = filePath.Substring (63); '. – npinti

ответ

2

Строки в C# неизменны (когда строка создается она не может быть изменен), то это означает, что при установке string cutpath = filepath вы устанавливают значение cutpath на path.Value, так как вы не присвоили значение filepath.SubString(63) ни к чему. Чтобы исправить это изменение

string filePath = path.Value; 
filePath.Substring(63); // here is the problem 
string cutPath = filePath; 

Для

string filePath = path.Value; 
string cutPath = filePath.Substring(63); 
0

Первое:

// It's do nothing 
filePath.Substring(63); 

// Change to this 
filePath = filePath.Substring(63); 

Второе:

63 is the character I was to substring from the file path for every entry looks like this: /GEM4/trunk/src/Tools/TaxMarkerUpdateTool/Tax Marker Ripper v1 with the final bit the real information i want to be shown which is: /DataModifier.cs

Это плохая идея использовать 63. Лучше найти в прошлом «/ "и сохраните его в некоторой переменной.

0

Спасибо Всем за помощь

Мой код теперь работает и выглядит следующим образом:

Private Dictionary<string,int> CreateDictionary(log logInstance) 
    { 
     Dictionary<string, int> dictionary = new Dictionary<string, int>(); 
     for (int entryIdex = 0; entryIdex < logInstance.logentry.Count(); entryIdex++) 
     { 
      logLogentry entry = logInstance.logentry[entryIdex]; 
      for (int pathIdex = 0; pathIdex < entry.paths.Count(); pathIdex++) 
      { 
       logLogentryPath path = entry.paths[pathIdex]; 
       string filePath = path.Value; 

       if (filePath.Length > 63) 
       { 
        string cutPath = filePath.Substring(63); 
        if (dictionary.ContainsKey(cutPath)) 
        { 
         dictionary[cutPath]++; 
        } 
        else 
        { 
         dictionary.Add(cutPath, 1); 
        } 
       } 
      } 
     } 
     return dictionary; 
    } 
0

Чтение ваши комментарии, по-видимому, вы просто хотите имя файла из пути к файлу. Существует встроенная утилита для достижения этого на любом пути.

Из MSDN:

Path.GetFileName

Returns the file name and extension of the specified path string.

https://msdn.microsoft.com/en-us/library/system.io.path.getfilename%28v=vs.110%29.aspx

Вот пример кода, чтобы вы начали.

string path = @"/GEM4/trunk/src/Tools/TaxMarkerUpdateTool/Tax Marker Ripper v1/Help_Document.docx"; 

string filename = System.IO.Path.GetFilename(path); 

Console.WriteLine(filename); 

Выход

Help_Document.docx

А вот ваш код с модификацией;

Private Dictionary<string,int> CreateDictionary(log logInstance) 
    { 
     Dictionary<string, int> dictionary = new Dictionary<string, int>(); 
     for (int entryIdex = 0; entryIdex < logInstance.logentry.Count(); entryIdex++) 
     { 
      logLogentry entry = logInstance.logentry[entryIdex]; 
      for (int pathIdex = 0; pathIdex < entry.paths.Count(); pathIdex++) 
      { 
       logLogentryPath path = entry.paths[pathIdex]; 
       string filePath = path.Value; 

       // extract the file name from the path 
       string cutPath = System.IO.Path.GetFilename(filePath); 

       if (dictionary.ContainsKey(cutPath)) 
       { 
        dictionary[cutPath]++; 
       } 
       else 
       { 
        dictionary.Add(cutPath, 1); 
       } 
      } 
     } 
     return dictionary; 
    } 
Смежные вопросы