C# Processing Fixed Width Files

这一生的挚爱 提交于 2019-11-29 15:40:31

Below example how to write in csv file (excel type), the main point is you need to read the first line and calculate width:

var lines = File.ReadLines("C:\\input.txt");

var widthList = lines.First().GroupBy(c => c)
                             .Select(g => g.Count())
                             .ToList();

var list = new List<KeyValuePair<int, int>>();

int startIndex = 0;

for (int i = 0; i < widthList.Count(); i++)
{
    var pair = new KeyValuePair<int, int>(startIndex, widthList[i]);
    list.Add(pair);

    startIndex += widthList[i];
}

var csvLines = lines.Select(line => string.Join(",", 
                    list.Select(pair => line.Substring(pair.Key, pair.Value))));

File.WriteAllLines("C:\\test.csv", csvLines);

You can use TextReader.Read method. For example:

    string input; // Test string

    // Replace new StringReader with a StreamReader to read a file
    using (TextReader textReader = new StringReader(input))
    {
        // Read first line to get structure
        var groupings = textReader.ReadLine().GroupBy(x => x);

        while (textReader.Peek() != -1)
        {
            // Convert to a string for easier handling than char[]
            List<string> fields = new List<string>();

            // Get the fields on each ling
            foreach (IGrouping<char, char> grouping in groupings)
            {
                char[] field = new char[grouping.Count()];
                textReader.Read(field, 0, field.Length);
                fields.Add(new string(field));
            }

            // Do something with "fields". The name of each field is
            // in grouping.Key at the same index.

            // Move to next line
            textReader.ReadLine();
        }
    }

Use the class TextFieldParser type per this how-to for Visual Basic.

You'll need to tell it the widths of the fields. Given your first line, that's easy enough.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!