views:

71

answers:

3

Lets say i have a text file with following content:

Hello!
How are you?

I want to call the file via a simple application that produces an output file with the following contents:

buildLetter.Append("Hello!").AppendLine(); 
buildLetter.Append("How are you?").AppendLine();

As you see, every line should be put between " ".

Any help will be appreciated.

+4  A: 
void ConvertFile(string inPath, string outPath)
{
    using (var reader = new StreamReader(inPath))
    using (var writer = new StreamWriter (outPath))
    {
        string line = reader.ReadLine();
        while (line != null)
        {
            writer.WriteLine("buildLetter.Append(\"{0}\").AppendLine();",line.Trim());
            line = reader.ReadLine ();    
        }
    }
}

You should add some I/O exception handling on your own.

jethro
Nitpicking: You could remove a `{}` pair and an indentlevel between the using statements. This notation doesn't scale well to to 3+ resources.
Henk Holterman
done also change !string.IsNullOrEmpty(line) to line != null to handle empty lines in input file.
jethro
I will try it and let you know!
Beginner_Pal
Works great! How can i ignore spaces between the word e.g. --- Hello!so the word between quotation occurs as " Hello!" .... How can i let the word occur as "Hello!" without spaces? .... Thanks alot
Beginner_Pal
added `.Trim()` to `writer.WriteLine` it removes spaces from beginning and end of line.
jethro
Solved....Thanks
Beginner_Pal
+3  A: 

If you want to append "" to each line you could try combining the ReadAllLines and WriteAllLines methods:

File.WriteAllLines(
    "output.txt",
    File
        .ReadAllLines("input.txt")
        .Select(line => string.Format("\"{0}\"", line))
        .ToArray()
);

Notice that this loads the whole file contents into memory so it wouldn't work well with very large files. In this case stream readers and writers are more adapted.

Darin Dimitrov
I would replace the "\"" + line + "\"" with string.Format("{0}{1}{0}", "\"", line)
Shimmy
Thanks ........
Beginner_Pal
A: 

Use the StreamReader class from System.IO

Refer this link for sample code

All you probably need to do is change the line

Console.WriteLine(sr.ReadLine());

to

Console.WriteLine(""""" + sr.ReadLine() + """"");  // handwritten code - not tested :-)
InSane