jhonny625 jhonny625 - 1 year ago 92
C# Question

how can sort alphabetically a text file?

I'm trying to sort a text file

with text like that








I need to sort but this code is not working

using System;
using System.IO;

class myclass
static void Main()
string infile = File.ReadAllText(@"C:\Users\diego\Desktop\finalregex.txt");
string outfile = File.ReadAllText(@"C:\Users\diego\Desktop\finalregex.txt");
var contents = File.ReadAllLines(infile);
File.WriteAllLines(outfile, contents);

please help me

Answer Source

Assuming the format in your example, this should suffice:

// File paths.
const string inFile = "in.txt";
const string outFile = "out.txt";

// Read file.
var inContents = File.ReadAllText(inFile);

// Organize contents.
var contentsArray = inContents.Replace(Environment.NewLine, ",")
    .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

// Sort contents.
var sortedContents = contentsArray.OrderBy(c => c);

// Write file.
File.WriteAllText(outFile, string.Join(",", sortedContents));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download