jhonny625 jhonny625 - 3 months ago 22
C# Question

how can sort alphabetically a text file?

I'm trying to sort a text file

with text like that

word1,word2,word3

word1,word2,word3

word1,word2,word3

.

.

.

word5,word6,word3

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);
Array.Sort(contents);
File.WriteAllLines(outfile, contents);
}
}


please help me

Answer

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));
Comments