2015-03-13 40 views
-1

我明白這種類型的問題已被問了很多次,但我似乎無法做到正確。我確實有一個路徑C:\ Users \ User1 \ Desktop \ Tutorial演練\ WindowsFormsApplication1 \ WindowsFormsApplication1 \ bin \ Debug。任何想法如何我可以從中刪除子字符\ bin?目前我已得到以下代碼從字符串向前移動字符串

string DirDebug = System.IO.Path.GetFullPath(".\\"); 
     int i = DirDebug.IndexOf("\bin"); 
     DirDebug = DirDebug.Remove(i); 
     MessageBox.Show(DirDebug) 

但它沒有顯示我想要的。任何想法如何我可以實現C:\用戶\用戶1 \桌面\教程演練\ WindowsFormsApplication1 \ WindowsFormsApplication1?任何幫助將不勝感激,先謝謝你。

+0

什麼_does_這說明了什麼? – CodeCaster 2015-03-13 11:33:07

+0

您需要將'\ bin'轉義爲'\\ bin'。 – Lloyd 2015-03-13 11:33:15

+1

這聽起來就像是一個完美的例子,你可以提供:a)一個簡短但完整的程序,例如控制檯應用程序; b)預期產出; c)實際產出。理想情況下 – 2015-03-13 11:33:34

回答

2

您可以使用DirectoryInfo class

string path= @"C:\Users\User1\Desktop\Tutorial Walkthrough\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug"; 
string rootDir = new DirectoryInfo(path).Parent.Parent.FullName; 

結果是:

C:\Users\User1\Desktop\Tutorial Walkthrough\WindowsFormsApplication1\WindowsFormsApplication1 

順便說一句,如果你想爲你的當前應用程序路徑,您可以使用Directory.GetCurrentDirectory

string rootDir = new DirectoryInfo(Directory.GetCurrentDirectory()).Parent.Parent.FullName; 

爲了完整起見,如果我想要一個普通的字符串a你可以使用這個方法:

string[] token = path.Split(Path.DirectorySeparatorChar); 
var allButTwoLast = token.Take(token.Length - 2); 
string result = string.Join(Path.DirectorySeparatorChar.ToString(), allButTwoLast); 
0

好的,抱歉的混淆。我確實有一個路徑C:\ Users \ User1 \ Desktop \ Tutorial演練\ WindowsFormsApplication1 \ WindowsFormsApplication1 \ bin \ Debug。但是我想從\ bin開始刪除子字符串,而Tim Schmelter先生剛剛解決了我的問題。謝謝!

string DirDebug = System.IO.Path.GetFullPath(「。\」);
string newpath = new DirectoryInfo(DirDebug).Parent.Parent.FullName; MessageBox.Show(newpath);

上面是解決

+0

如果他這樣做,upvote他的帖子和/或接受爲答案:)。 – bokibeg 2015-03-13 11:47:41

+0

是的,我剛剛做到了!感謝您的提醒 – user3340537 2015-03-13 11:55:38