简体   繁体   中英

C# Create multiple .txt files using strings from another file and textbox

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.

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.)

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM