2011-04-13 69 views
3

我有一個正在做文件複製的方法。 'root'由用戶在命令行上指定,我用Path.GetFullPath(input)進行清理。如何獲取相對文件名到特定目錄?

我需要得到相對於根的文件的路徑,所以下面的情況下,將返回:

Root  FilePath     Return 
y:\   y:\temp\filename1.txt  temp\filename1.txt 
y:\dir1  y:\dir1\dir2\filename2.txt dir2\filename2.txt 

回答

1
System.IO.Path.GetFullPath(filePath).Substring(rootPath.Length) 
+0

'System.IO.Path.GetFullPath(filePath).Substring(System.IO.Path.GetFullPath(rootPath).Length)'會更安全我想 - 在假定rootPath的長度爲兩個字符串都相同。 – Hutch 2015-04-16 21:42:42

1
string relativePath = Path.GetFullPath(input).Replace(rootPath, ""); 
1
string s1 = "y:\\"; 
string s2 = "y:\\temp\filename1.txt"; 
Console.WriteLine(s2.Substring(s1.Length)); \\ Outputs temp\filename1.txt 

希望這有助於

可能還想調用.Trim()以確保刪除尾隨\字符等。

+0

你的意思是'.TrimEnd' – SLaks 2011-04-13 22:08:10

+0

Nah我的意思是http://msdn.microsoft.com/en-us/library/d4tt83f9.aspx實際的方法與原型和所有..但如果你想只是爲了做到這一點一邊是TrimStart ...文件名不能有\,但它可能在子文件夾路徑的路徑開始處。 – James 2011-04-13 22:17:30

相關問題