[英]C# Reading file and pulling out specific lines
提前致謝。 我目前擁有的是一個文件對話框,用於選擇文本文件。 文本文件的內容將類似於example.txt,而其外觀則類似於output.txt。 注意:字符串CoreDBConnectString=
是1行;Database=Source_DB.
一直到;Database=Source_DB.
example.txt [Information] Date= CreatedBy= Unique=eqwe-asd-123-as12-3 CoreDataSource= CoreDBConnectString=Provider=SQLOLEDB.1;Server=Server;Integrated Security=SSPI;Database=Source_DB NoteDataSource=SQLServer NoteDBConnectString=Provider=Provider=SQLOLEDB.1;Server=Server;Integrated Security=SSPI;Database=Source_DB CoreDBCaseID=99 NoteDBCaseID=99 Output.txt Table=99 (Comes from CoreDBCaseID) Server=Server (comes from the string CoreDBConnectString=) Security=SSPI (comes from the string CoreDBConnectString=) Database=Source_DB (comes from the string CoreDBConnectString=)
您可以執行以下操作:
// Load the file contents
string contents = File.ReadAllText("example.txt");
// Obtain the data using regular expressions
string id = string id = Regex.Match(
contents,
@"CoreDBCaseID=(?<id>\d+)").Groups["id"].Value;
string server = string.Empty; // Add regex here
string security = string.Empty; // Add regex here
string database = string.Empty; // Add regex here
// Save the data in the new format
string[] data = new string[] {
String.Format("Table={0}", id),
String.Format("Server={0}", server),
String.Format("Security={0}", security),
String.Format("Database={0}", database)
};
File.WriteAllLines("output.txt", data);
一種學習這些正則表達式的快速方法:
您可以使用正向前瞻停止在(;)字符處的匹配。 像這樣:
@ “安全=([\\ d] +?)(=;?)”
那是一個INI文件,非常老派。 如今,我們編程人員改用XML。 因此,C#中沒有對INI文件的內置支持。
您可以P /調用 GetPrivateProfileString來讀取數據。
如果您不介意像這樣的信息部分標題,則可以使用WritePrivateProfileString將新數據寫出:
[Information]
Table=99
Server=Server
Security=SSPI
Database=Source_DB
這篇有關使用C#進行INI文件處理的CodeProject文章可能會有所幫助。
我將結合使用StreamReader.ReadLine
和RegEx
讀取每一行並提取適當的信息。
打開文件並一次一行讀取它。 您可以使用正則表達式(備忘單)來匹配和解析僅要查找的文本。
INI文件是老套。 因此,已經有人為其編寫了一個類: http : //www.codeproject.com/KB/cs/readwritexmlini.aspx 。 鏈接的類讀取XML,INI,注冊表和配置文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.