2017-04-11 8 views
0

DirectoryPath = C:PicsのC#フィルターの違い

filePath = C:\ Picsの\ \犬\ 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

LastIndexOf()から得られるインデックスは、常にケース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

あなたはファイルパスにディレクトリ・パス&にバックスラッシュを追加でしdirectorypathにはNEWPATH、その後、filePathに開始と一致しない場合は、空の文字列

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

とディレクトリパスを交換します変更されません。

コードを編集してバックスラッシュの条件付き追加を表示する前にこれを投稿しました。これを上記のコードで削除することができます。

+0

あなたの答えをありがとう! –

2

filePathDirectoryPathが含まれている場合は、私が最初に確認しますので、私はこのような何かしたい:使用していても

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

orベターを、StartsWith

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

ありがとうございました! –