我想讀取info1.txt檔案,并想以這種方式寫入另一個文本檔案info2.txt。
Id Name Address DOB Phone
1 abcd efg 1/16/2021 987654323
2 hijkl mno 2/16/2021 678987652
info1.txt檔案的內容如下:
Id:1
Name:abcd
Address:efg
DOB:1/16/2021 3:31:22 PM
Phone:987654323
而info2.txt就像我提到的上述表格格式,也想洗掉“3:31:22 PM”。我為解決這個問題而開發的代碼塊如下:
static void Main(string[] args)
{
FileStream fsRead = new FileStream("E:\\info1.txt", FileMode.Open, FileAccess.Read);
StreamReader srObj = new StreamReader(fsRead);
FileStream fsWrite = new FileStream("E:\\info2.txt", FileMode.Create, FileAccess.Write);
StreamWriter swObj = new StreamWriter(fsWrite);
while (srObj.Peek() > 0)
{
string str;
string[] strArray;
str = srObj.ReadLine();
str = str.Replace(" 3:31:22 PM", "");
strArray = str.Split(':');
if (strArray.Length > 1)
{
swObj.Write(strArray[1]);
swObj.Write(" ");
}
}
swObj.Close();
fsWrite.Close();
srObj.Close();
fsRead.Close();
Console.ReadKey();
}
uj5u.com熱心網友回復:
我會將檔案決議為字典串列,其中每個字典的鍵是列。
首先將檔案行拆分為字串陣列。你可以用File.ReadAllLines它。然后將陣列發送到決議這些行的函式。
public static List<Dictionary<string, string>> Parse(string [] lines)
{
List<Dictionary<string, string>> data = new List<Dictionary<string, string>>();
Dictionary<string, string> temp = new Dictionary<string, string>();
foreach (var line in lines) {
var parts = line.Split(new[] { ':' }, 2);
if (parts.Length == 2) {
temp[parts[0]] = parts[1];
}
else {
if (temp.Count > 0) data.Add(temp);
temp = new Dictionary<string, string>();
}
}
if (temp.Count > 0) data.Add(temp);
return data;
}
然后,創建一個函式將串列寫入檔案。
public static void PrintTable(List<Dictionary<string, string>> users, TextWriter stream)
{
if (users.Count == 0) return;
// Print the header line
foreach(var pair in users[0]) {
stream.Write("{0,-12}", pair.Key);
}
stream.WriteLine();
foreach (var user in users) {
foreach(var pair in user) {
// Special handling for DOB
if (pair.Key == "DOB") stream.Write("{0,-12}", pair.Value.Split(' ')[0]);
else stream.Write("{0,-12}", pair.Value);
}
stream.WriteLine();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/382512.html
