我有一個正在做文件複製的方法。 '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
我有一個正在做文件複製的方法。 '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
你可以寫
var relative = new Uri(rootPath).MakeRelativeUri(new Uri(filePath));
http://msdn.microsoft.com/en-us/library/system.uri.makerelativeuri.aspx
System.IO.Path.GetFullPath(filePath).Substring(rootPath.Length)
'System.IO.Path.GetFullPath(filePath).Substring(System.IO.Path.GetFullPath(rootPath).Length)'會更安全我想 - 在假定rootPath的長度爲兩個字符串都相同。 – Hutch 2015-04-16 21:42:42
string relativePath = Path.GetFullPath(input).Replace(rootPath, "");
string s1 = "y:\\";
string s2 = "y:\\temp\filename1.txt";
Console.WriteLine(s2.Substring(s1.Length)); \\ Outputs temp\filename1.txt
希望這有助於
可能還想調用.Trim()以確保刪除尾隨\字符等。
把它變成「../」這似乎沒有關係? – esac 2011-04-13 22:14:45
對於什麼輸入? – SLaks 2011-04-13 22:18:40
rootPath = y:\,filePath = y:\ 2010-05 \ DSC_154.JGP – esac 2011-04-13 22:20:16