2017-04-11 46 views
0

DirectoryPath = C:\照片管理C#篩選差異

filePath= C:\照片管理\狗\ dog.PNG

newPath應該是:狗\ dog.PNG


如何獲得newPath? 我的代碼片段是無法事先正確


string directoryPath = "C:\\Pics"; 
string filePath = "C:\\Pics\\Dogs\\dog.PNG"; 

if (!directoryPath.EndsWith("\\")) 
    directoryPath = directoryPath + "\\"; 

string newPath = filePath.Substring(filePath.LastIndexOf(directoryPath) + 1); 

謝謝!

+2

貌似[XY問題的情況下, ](https://meta.stackexchange.com/a/66378/208223)。你確定你想要的字符串的差異,而不是相對路徑? – Theraot

+0

'LastIndexOf'和'IndexOf'返回子字符串開始的索引,而不是結束的地方。 – juharr

回答

3

intLastIndexOf()得到的索引將始終以最右邊的值開始,在您的情況下爲0.您還需要爲此添加String.Lenght

if (filePath.StartsWith(directoryPath)) 
{ 
    string newPath = 
     filePath.Substring(filePath.LastIndexOf(directoryPath) + directoryPath.Length + 1); 
} 
+1

您應該檢查原始文件路徑的開頭與目錄路徑是否匹配。 – PaulF

+1

有了這段代碼,你不能在'if'之外使用'newpath' :) – Pikoh

+0

@Pikoh我不想讓它太OP容易;) – Smartis

3

你能附加一個反斜槓的目錄路徑&然後在文件路徑爲空字符串

newPath = filePath.Replace(DirectoryPath + @"\", string.Empty); 

更換目錄路徑。如果目錄路徑沒有文件路徑的開始匹配,那麼NEWPATH將保持不變。

在您編輯代碼以顯示有條件的反斜槓添加之前,我已經發布了這個消息 - 這樣可以在上面的代碼中刪除。

+0

謝謝你的回答! –

2

我會首先檢查是否filePath包含DirectoryPath,所以我會做這樣的事情:

var newPath=filePath.Contains(DirectoryPath)?filePath.Substring(DirectoryPath.Length + 1) 
              :filePath; 

甚至更​​好,使用StartsWith

var newPath=filePath.StartsWith(DirectoryPath)?filePath.Substring(DirectoryPath.Length + 1) 
              :filePath; 
+0

謝謝你的回答! –