views:

491

answers:

3

Hello to all. I am new to programming. Is there a way to create multiple .txt files using
data from another file in C#.
like this:
1. we have data.txt with 100 or more strings
string1
string2
string3

...
2. we have textbox1 and textbox2 waiting for user to enter strings

3 . we need to create 100 or more files using strings from data.txt and textboxes strings: name of the fisrt file : string1+textbox1string.txt
and inside it we write: textbox2string + string1 + textbox1string
the same pattern to create other files, second - string2+textbox1string.txt and inside second - textbox2string + string2 + textbox1string
sorry for my english i am not native speaker.

+3  A: 

Well, it sounds like you want something like:

string[] lines = File.ReadAllLines("file1.txt");
foreach (string line in lines)
{
    File.WriteAllText(line + textbox1.Text + ".txt",
                      textbox2.Text + line + textbox1.Text);
}

Basically for very simple tasks like this, the methods in the File class allow "one shot" calls which read or write whole files at a time. For more complicated things you generally have to open a TextReader/TextWriter or a Stream.

If this wasn't what you were after, please provide more information. Likewise if you find the code hard to understand, let us know and we'll try to explain. You may fine it easier with more variables:

string[] lines = File.ReadAllLines("file1.txt");
foreach (string line in lines)
{
    string newFile = line + textbox1.Text + ".txt";
    string fileContent = textbox2.Text + line + textbox1.Text;
    File.WriteAllText(newFile, fileContent);
}

EDIT: If you want to add a directory, you should use Path.Combine:

string newFile = Path.Combine(directory, line + textbox1.Text + ".txt");

(You can do it just with string concatenation, but Path.Combine is a better idea.)

Jon Skeet
Thank you for fast reply. Your code is fantastic! I was searching for it very long :) If its possible can you write how can we add the path to directory in which to create files please.
new_coder
A: 

Look into the static File class. It will have a lot of what you want.

http://msdn.microsoft.com/en-us/library/6ka1wd3w.aspx

Dested
A: 

Sure...

string textbox1string = textbox1.Text, textbox2string = textbox2.Text;
foreach(string line in File.ReadAllLines("data.txt")) {
    string path = Path.ChangeExtension(line + textbox1string, "txt");
    File.WriteAllText(path, textbox2string  + line + textbox1string);
}
Marc Gravell