簡體   English   中英

如何在C#中處理此文件?

[英]How can I process this file in C#?

我有一個包含數百個這樣格式的條目的文本文件,我需要在數據網格上顯示此文件,或者根據您的建議“正確格式化”其他用戶友好控件。 (我的意圖是將其導出為ex​​cel 而不是最佳選擇,但需要進一步處理。所有列都是以毫秒為單位的值,因此大多數時候這些值都非常大,最多可達3小時,所以我需要將它們轉換為小時/分鍾/秒。)處理此任務的最佳方法是什么? 可以使用StreamReader完成嗎? 轉換是否可以在代碼中進行,因此無需導出到Excel? 有樣品嗎? 謝謝!

  ENTRY DAY ENTRY TIME  IN.WORK   TEST %     TRY CORRER     CORTA   CICLO MAQUI
    O0.TXT            
      11/07/28  13:39:13        0        0     105       0       0       0       0
    O0.TXT            
      11/07/20  00:00:00        0        0   19145       0       0       0       0
    O0.TXT            
      11/07/19  15:04:10        0        0   32151       0       0       0       0

我想格式化它:

FILE   ENTRY DAY ENTRY TIME  IN.WORK   TEST %   TRY    CORRER   CORTA   CICLO   MAQUI
O0.TXT 11/07/28  13:39:13        0        0     105       0       0       0       0
O0.TXT 11/07/20  00:00:00        0        0   19145       0       0       0       0
O0.TXT 11/07/19  15:04:10        0        0   32151       0       0       0       0
O0.TXT 11/07/07  05:22:40        0        0     508       0       0       0       0

我試過用:

string fileName = "Myfile.txt";
StreamReader sr = new StreamReader(fileName);
string[] delimiter = new string[] { " " };
while (!sr.EndOfStream)
{
     string[] lines = sr.ReadLine().Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
     foreach (string line in lines)
     { 

........

但是我根本無法保存我想要的格式,也沒有將它加載到數據網格等等。

string fileName = "Myfile.txt";

string[] delimiter = new string[] { " " };

List<string[]> rows = new List<string[]>();

string[] liens = File.ReadAllLines(fileName);

foreach (string line in liens)
{
    rows.Add(line.Split(delimiter, StringSplitOptions.RemoveEmptyEntries));
}

//Now if you want to display them each one row item separated by tab "`\t"` or csv `","`
string separator = "\t";

List<string> output = new List<string>();

foreach (string[] row in rows)
{
    output.Add(string.Join(separator, row));
}

string newFile = "result.txt";
File.WriteAllLines(newFile, output.ToArray());//save the output to new file.

一切都固定了嗎? 例如,日期總是6個字符和8個字符長(或者不管是什么情況)? 如果是這樣,我會拆分“\\ r \\ n”而不是“”,然后單獨處理每一行。 你可以這樣做:

string fileName = "Myfile.txt";
StreamReader sr = new StreamReader(fileName);
string[] delimiter = new string[] { "\r\n" };
while (!sr.EndOfStream)
{
    string[] lines = sr.ReadLine().Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
    foreach (string line in lines)
    { 
        date = line.Substring(6, 8);
        // Do the other processing here.
    }
}

當然,您必須為需要處理的行提供一些邏輯。

暫無
暫無

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

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