c# help

Associate
Joined
30 Sep 2004
Posts
1,038
Location
Colchester, Essex
I have a list of filenames in a variable (seperated by newlines) and I want to merge them all into one file with a specified file name. How would I do that? (by merge, I mean copy the first one to newfilename and then append the second and third and so on)
 
If i understand you correctly you have all the filenames (separated by new lines) stored in a single variable? Is this a string type? If so, can't you just output that string to the desired file and that is the end of it?
 
If im understanding your problem correctly, how about this:

Code:
string filesString = "file1.txt\nfile2.txt\nfile3.txt";
string[] fileNames = filesString.Split('\n');

System.IO.StreamWriter writer;
writer = System.IO.File.CreateText("files.txt");

foreach(string file in fileNames)
{
    writer.WriteLine(file);
}

writer.Close();


EDIT: Unless you meant that you wanted to write the contents of each file to a new file, in which case:

Code:
string filesString = "file1.txt\nfile2.txt\nfile3.txt";
string[] fileNames = filesString.Split('\n');

foreach (string file in fileNames)
{
    System.IO.StreamReader reader = System.IO.File.OpenText(file);
    string contents = reader.ReadToEnd();

    System.IO.StreamWriter writer = System.IO.File.AppendText("newFile.txt");
    writer.WriteLine(contents);

    reader.Close();
    writer.Close();
}
 
Last edited:
You could look into the serialization (sic) tools available in C#. I am not 100% sure but I don't think you will be able to simply 'merge' different binary files into 1 big file without first deserializing the individual files and then serializing the array of objects you created - like I said though, im not sure :P

not entirely sure why im posting this...
 
I managed to make it work with the following nifty bit of code:
Code:
foreach (string fileWithR in fileNames)
{
	if (fileWithR.Length != 0)
	{
		string file = fileWithR.Substring(0, fileWithR.Length - 1);
		using (FileStream readfs = File.OpenRead(file)) using (FileStream writefs = new FileStream(outputFileNames[z], FileMode.Append, FileAccess.Write))
		{
			int b; byte[] buffer = new byte[10240];
			while ((b = readfs.Read(buffer, 0, 10240)) > 0) writefs.Write(buffer, 0, b);
		}
	}
}
 
Back
Top Bottom