簡體   English   中英

如何從C#的完整路徑中獲取一部分?

[英]How to get a part from the full path in C#?

我有一個完整的路徑,如下所示。

C:\Users\Ronny\Desktop\Sources\Danny\kawas\trunk\csharp\ImportME\XukMe\bin\Debug\DannyGoXuk.DTDs.xhtml-math-svg-flat.dtd

如何從這整個部分中獲取DTD“部分”?

期望的輸出:

C:\Users\Ronny\Desktop\Sources\Danny\kawas\trunk\csharp\ImportME\XukMe\bin\Debug‌​\DannyGoXuk.DTDs

我可以使用String的方法嗎?
如果是,那么如何獲取它?

System.IO.Path.GetDirectoryName()用於整個路徑,或使用new DirectoryInfo(path).Parent.Name作為該文件夾的名稱。


您發布的路徑中沒有名為“DTD”的目錄。 它看起來像有一個文件名為"DannyGoXuk.DTDs.xhtml-math-svg-flat.dtd" ,但在這條道路的句號(。)是不是有效的目錄分隔符。 你的意思是"DannyGoXuk\\DTDs\\xhtml-math-svg-flat.dtd"

如果是這種情況, 假定整個新路徑 ,你想要這樣的東西返回DTDs文件夾中的文件列表:

string path = @"C:\Users\Ronny\Desktop\Sources\Danny\kawas\trunk\csharp\ImportME\XukMe\bin\Debug\DannyGoXuk\DTDs\xhtml-math-svg-flat.dtd";
string[] files = new DirectoryInfo(path).Parent.GetFiles();

在屬性窗口中,我選擇Build Type作為嵌入式資源。

現在我們終於明白了。 選擇“嵌入式資源”時,該項目將捆綁到可執行程序文件中。 沒有直接的路徑了 而是將您的構建類型設置為“內容”並將“復制到輸出目錄”設置為“始終復制”或“如果更新則復制”。

調用

System.IO.Path.GetFileName

使用完整目錄路徑返回路徑的最后一部分,即目錄名稱。 GetDirectoryName返回不需要的父目錄的完整路徑。

如果您有文件名,並且只想要父目錄的名稱:

var directoryFullPath = Path.GetDirectoryName(@"C:\DTDs\mydtd.dtd");  // C:\DTDs
var directoryName = Path.GetFileName(directoryFullPath);  // DTDs

您還可以使用Directory從完整文件路徑獲取目錄:

Directory.GetParent(path).FullName

編輯:請在下載之前仔細閱讀OP的問題及其所有評論。 OP的標題問題並不完全是她想要的。 我的回答給了她解決問題所需要的東西。 這就是為什么她投票給答案的原因。 是的,如果專門回答標題問題,Joel的回答是正確的。 但在閱讀她的評論之后,你會發現她並不完全是在尋找什么。 謝謝。

用這個 ...

string strFullPath = @"C:\Users\Ronny\Desktop\Sources\Danny\kawas\trunk\csharp\ImportME\XukMe\bin\Debug\DannyGoXuk.DTDs.xhtml-math-svg-flat.dtd";
string strDirName; 
int intLocation, intLength;

intLength = strFullPath.Length;
intLocation = strFullPath.IndexOf("DTDs");

strDirName = strFullPath.Substring(0, intLocation); 

textBox2.Text = strDirName;

使用:

string dirName = new DirectoryInfo(fullPath).name;
System.IO.Path.GetFileName( System.IO.Path.GetDirectoryName( fullPath ) )

這將只返回包含該文件的文件夾的名稱。

對於

C:\windows\system32\user32.dll

這將回來

system32

我推斷那就是你想要的。

您可以使用:

System.IO.Path.GetDirectoryName(path);

你可以使用Path ...

Path.GetDirectoryName(myStr);

不要直接使用字符串操作。 而是使用Path類的GetDirectoryName

System.IO.Path.GetDirectoryName(myPath);

使用FileInfo對象...

FileInfo info = new FileInfo(@"C:\Users\Ronny\Desktop\Sources\Danny\kawas\trunk\csharp\ImportME\XukMe\bin\Debug\DannyGoXuk.DTDs.xhtml-math-svg-flat.dtd");
string directoryName = info.Directory.FullName;

該文件甚至不必存在。

您指定的路徑上的Path.GetDirectory返回:

“C:\\用戶\\羅尼\\桌面\\源\\丹尼\\卡瓦斯\\干線\\ CSHARP \\ ImportME \\ XukMe \\ BIN \\調試”

親自嘗試一下:

var path = Path.GetDirectoryName(@"C:\Users\Ronny\Desktop\Sources\Danny\kawas\trunk\csharp\ImportME\XukMe\bin\Debug\DannyGoXuk.DTDs.xhtml-math-svg-flat.dtd");

你的問題有點奇怪 - 沒有名為DTD的目錄。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM