需要帮助在 C# 中格式化一个单独的 .txt 文件。我有一个包含目录列表的文本文件,当我在记事本或 ultra-edit 中打开时,它看起来如下所示。第一列是日期和时间,下一列是文件大小(以字节为单位),第三列是用户名,第四列是文件名。每列由一个或多个空格分隔,末尾的文件名列可以在文件名中包含空格。它们由更多的目录组成,文件中的总行数约为 200,000。
Directory of V:\word
01/10/2013 12:30 PM 23,000 BUILTIN/ADMINISTRATOR FILE NAME.XLS
10/25/2013 10:39 AM 1,332,432 AMERICAS/DOEJ FILENAME2.CSV
11/31/2000 09:54 PM 21,999,999 AMERICAS/DOEF F_I_L_E_N_A_M_E_4.PDF
Directory of V:\word\administrators
01/10/2013 12:30 PM 23,000 BUILTIN/ADMINISTRATOR FILENAME.XLS
10/25/2013 10:39 AM 1,332,432 AMERICAS/DOEJ FILENAME2.CSV
11/31/2000 09:54 PM 21,999,999 AMERICAS/DOEF F_I_L_E_N_A_M_E_4.PDF
我的目标是尝试在文件名末尾以固定格式添加目录路径(例如 V:\Word 或其他目录)。因此,一旦您看到“Directory V:\word”,您就会知道新目录之后和之前的每一行,应该在文件名末尾显示该路径。这将被视为第五列。
这是一些代码,但我仍然需要帮助。我能够在文件末尾获取 V:\word,但如何读取新目录并将其附加到所有后续行的行尾?
private void button1_Click(object sender, EventArgs e)
{
var sbText = new StringBuilder(10000);
string currLine = " Directory of V:\\word ";
try
{
using (StreamReader Reader = new StreamReader(@"C:\V.txt"))
{
while (!Reader.EndOfStream)
{
if (currLine != " Directory of V:\\word ")
{
MessageBox.Show("No Directory");
}
else
{
sbText.AppendLine(Reader.ReadLine() + "V:\\word");
}
}
// When all of the data has been loaded, write it to the text box in one fell swoop
richTextBox1.Text = sbText.ToString();
using (StreamWriter Writer = new StreamWriter(@"C:\NEWFILE.txt"))
{
Writer.WriteLine(sbText);
}
}
}
catch (Exception ex)
{
MessageBox.Show("An error has occured. " + ex.Message);
}
最佳答案
这是一种相当直接的方法——它定义了一个代表您的数据的简单类,并将每一行解析为一个类实例。它非常高效,并且可以轻松地将结果写入新文件、查询或显示:
void Main()
{
var lines = ReadFile();
lines.ToList().ForEach (Console.WriteLine);
}
IEnumerable<Line> ReadFile()
{
using (var reader = new StreamReader(File.OpenRead(@"file.txt")))
{
const string directoryPrefix = " Directory of ";
Regex splittingRegex = new Regex(@"\s+", RegexOptions.Compiled);
string directory = null;
string line;
while ((line = reader.ReadLine()) != null)
{
line = line.TrimEnd();
if (line.StartsWith(directoryPrefix))
{
directory = line.Substring(directoryPrefix.Length);
continue;
}
// The "6" parameter means the regex will split the string into 6 parts at most--leaving the last column (filename) unsplit
var lineParts = splittingRegex.Split(line, 6);
yield return new Line{ Date = lineParts[0], Time = lineParts[1], Period = lineParts[2], Bytes = lineParts[3], User = lineParts[4], Filename = Path.Combine(directory, lineParts[5]) };
}
}
}
// Define other methods and classes here
class Line
{
public string Date{get;set;}
public string Time {get;set;}
public string Period {get;set;}
public string Bytes {get;set;}
public string User {get;set;}
public string Filename {get;set;}
}
注意:这是从几个用于解析简单文本文件的辅助方法派生出来的。 my earlier revisions之一包括可能对您有用的辅助方法(但由于需要记住 directory
值,因此不太适合此操作)。
关于c# - 重新格式化文件的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18472009/