Mario
Mario

Reputation:

Detect space and add a comma

I have text file with employes email like this below

[email protected]
[email protected]
[email protected]
[email protected]

I want change to like this

[email protected], [email protected], [email protected], [email protected]

How can i do using C# code?

Upvotes: 1

Views: 7974

Answers (6)

MarcE
MarcE

Reputation: 3731

I'd operate on the file directly to avoid the overhead of reading a potentially huge employee database into a string:

private static void MungeFile(string filename)
{
    FileStream fsOut = File.Create(filename+"_out");
    FileStream fsIn = File.OpenRead(filename);
    StreamReader sr = new StreamReader(fsIn);
    StreamWriter sw = new StreamWriter(fsOut);
    while (!sr.EndOfStream)
    {
        string inputLine = sr.ReadLine();
        string terminator = (sr.EndOfStream ? "" : ",");
        sw.Write(inputLine + terminator);
    }
    sw.Flush();
    fsOut.Close();
}

Upvotes: 1

Matthew Whited
Matthew Whited

Reputation: 22443

this would replace CR\LF and spaces with ','

string newContent = string.Join(",", 
                                File.ReadAllLines("sourceFile.txt")
                                ).Replace(' ', ',')

File.WriteAllText("newFile.txt", newContent);

Upvotes: 1

CmdrTallen
CmdrTallen

Reputation: 2282

Could do this;

    string linesFromFile = string.Empty;

    // Read into string from file
    using (StreamReader sr = new StreamReader("filename.txt"))
    {
        linesFromFile = sr.ReadToEnd();
        linesFromFile = linesFromFile.Replace(Environment.NewLine, ",");
        Console.WriteLine(linesFromFile);
    }

    // Write back from string to file
    using (StreamWriter sw = new StreamWriter("newFilename.txt"))
    {
        foreach(string s in linesFromFile.Split(','))
        {
            sw.WriteLine(s);
        }
    }

Upvotes: 3

Matthew Jones
Matthew Jones

Reputation: 26190

Read in the text file as a string, then do something like this to replace the newlines with a comma (replace Environment.NewLine with ' ' if you are looking to replace spaces):

String newFile = oldFile.Replace(Environment.NewLine,',');

Upvotes: 0

Dean J
Dean J

Reputation: 40298

Microsoft's documentation covers this one pretty well: http://msdn.microsoft.com/en-us/library/ms228599.aspx

Upvotes: 0

David Basarab
David Basarab

Reputation: 73301

string yourString = oldString.Replace(' ', ',');

Most likely it is not a space but a new line, so it would be

string yourString = oldString.Replace(Environment.NewLine, ",");

Upvotes: 4

Related Questions