C# 旧交换机IO(文件中的交换机位置)

C# 旧交换机IO(文件中的交换机位置),c#,winforms,string,text,switch-statement,C#,Winforms,String,Text,Switch Statement,如果有人能在这方面帮助我/提供建议,我将不胜感激 我有一个文件,大概有50000行长,这些文件是每周生成的。每一行内容的类型都是相同的 原始文件: address^name^notes 但我需要做一个转换。我需要能够切换每一行的地址与名称。因此,切换完成后,将首先显示名称,然后是地址,然后是注释,如下所示: 结果文件: name^address^notes 现在50000已经不是那么多了,所以只需读取整个文件并输出所需的格式就可以了: string[] lines = File.ReadAl

如果有人能在这方面帮助我/提供建议,我将不胜感激

我有一个文件,大概有50000行长,这些文件是每周生成的。每一行内容的类型都是相同的

原始文件:

address^name^notes
但我需要做一个转换。我需要能够切换每一行的地址与名称。因此,切换完成后,将首先显示名称,然后是地址,然后是注释,如下所示:

结果文件:

name^address^notes

现在50000已经不是那么多了,所以只需读取整个文件并输出所需的格式就可以了:

string[] lines = File.ReadAllLines(fileName);
string newLine = string.Empty;

foreach (string line in lines)
{
    string[] items = line.Split(myItemDelimiter);
    newLine = string.Format("{0},{1},{2}", items[1], items[0], items[2]);
    // Append to new file here...
}
去吧,小工具正则表达式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static string Switcheroo(string input)
        {
            return System.Text.RegularExpressions.Regex.Replace
                (input,
                 @"^([^^]+)\^([^^]+)\^(.+)$",
                 "$2^$1^$3",
                 System.Text.RegularExpressions.RegexOptions.Multiline);
        }

        static void Main(string[] args)
        {
            string input = "address 1^name 1^notes1\n" +
                     "another address^another name^more notes\n" +
                     "last address^last name^last set of notes";

            string output = Switcheroo(input);
            Console.WriteLine(output);
            Console.ReadKey(true);
        }
    }
}
这个怎么样

StreamWriter sw = new StreamWriter("c:\\output.txt");
        StreamReader sr = new StreamReader("c:\\input.txt");
        string inputLine = "";

        while ((inputLine = sr.ReadLine()) != null)
        {
            String[] values = null;
            values = inputLine.Split('^');
            sw.WriteLine("{0}^{1}^{2}", values[1], values[0], values[2]);
        }
        sr.Close();
        sw.Close();

您是否需要在适当的位置执行此操作,或者代码是否可以创建第二个文件,将交换的行放入其中?使用awk.awk执行此操作非常简单?太棒了,谢谢你的提示。现在查看:D+1Go gadget REGEX!-我喜欢这种热情:我建议不要使用ReadAllLines路线,如果有任何增长或重复使用此过程的机会,50K行可能会占用内存。Mick Walker的解决方案将确保不必使用内存。公平地说,这确实不会扩展到非常大的文件,在这方面Mick Walker有一个更好的解决方案。