2011-02-24 30 views
0

我需要一些基本的幫助。
我有一個文件夾,其中有一個文件。
在文件中,有兩行,行中的數據用「//」分隔。如何在.txt文件中顯示一部分行 - C#

實施例:

有一個夾在位置@ 「C:\ ExampleFolder_ABCD \」
在文件夾有一個文件@ 「C:\ ExampleFolder_ABCD \ ExampleFile_ABCD.txt」
在文件有兩條線:

NAME_1 // DESCRIPTION_1
NAME_2 // Description_2

我需要我的程序來顯示每行的第一部分,「//」之前的部分以及僅此部分。
我已經做了一些研究,但我指望一些實時幫助。

當然,任何幫助,無論好還是壞,都將不勝感激。
注意:這與家庭作業無關。它保存了我的一個項目,這將幫助我組織電話簿。

聖洛夫羅Mirnik

如果你覺得自己的測試,下面的代碼複製到一個新創建的命名空間,編輯和執行它。

string MainDirectoryPath = @"C:\ExampleFolder_ABCD\"; // Example directory path - Completely random name (100% no overwrite) 
string MainFileName = @"C:\ExampleFolder_ABCD\ExampleFile_ABCD.txt"; // Example file path - Completely random name (100% no overwrite) 
Directory.CreateDirectory(MainDirectoryPath); // Create the directory. 
StreamWriter CreateExampleFile = new StreamWriter(MainFileName); // Create the file. 
CreateExampleFile.Close(); // Close the process. 
StreamWriter WriteToExampleFile = File.AppendText(MainFileName); // Append text to the file. 
WriteToExampleFile.WriteLine("Name_1 // Description_1"); // This line to append. 
WriteToExampleFile.WriteLine("Name_2 // Description_2"); // This line to append. 
WriteToExampleFile.Close(); // Close the process. 
// 
// 
// I would like to know how to display both names in a list 
// without the Description part of the line. 
// Maybe with a command that contains "* // *" ?? 
+0

[String.Split](http://msdn.microsoft.com/en-us/library/tabh47cf%28v=VS.100%29.aspx)應該是有幫助的,以及[TextReader](http: //msdn.microsoft.com/en-us/library/system.io.textreader.aspx)(特別是[ReadLine](http://msdn.microsoft.com/en-us/library/system.io.textreader。 readline.aspx)) – 2011-02-24 23:41:38

回答

0

下面是一些代碼:

StreamReader Reader = new StreamReader(MainFileName); 
      char c = Convert.ToChar(@"/"); 
      Char[] splitChar = { c, c }; 
      String Line; 
      while (!Reader.EndOfStream) 
      { 
       Line = Reader.ReadLine(); 
       String[] Parts; 
       Parts = Line.Split(splitChar); 
       foreach (string s in Parts) 
       { 
        Console.WriteLine(s); 
       } 
      } 
      Reader.Close(); 
      Console.WriteLine("Done"); 
+0

太好了,謝謝! – 2011-02-25 09:38:39

0

我想你會發現所有你需要在這裏:http://www.dotnetperls.com/string-split

圍在中間有一堆代碼分割字符串從一個文本文件,你可以用一些替代分裂部後再使用像

Regex.Split(myline, "\\\\")[0] 

它應該像一個魅力。

0

從你發佈的例子中,你需要做的就是分割每條線"\\\\"(你將不得不避開斜槓)。採取分裂的第一個結果,你去了。

0

另一種變型,使用分方法的字符串對象上:

var result = myString.Split(new char[] {'/','/'})[0] 

只要拆分其中找到「//」到一個數組的字符串。然後你拉回數組中的第一個元素。