frenchie
frenchie

Reputation: 51927

creating and saving a file to a directory

I'm using a string builder to read several files from a directory like this:

StringBuilder sb = new StringBuilder();

sb.Append(System.IO.File.ReadAllText(
       HttpContext.Current.Server.MapPath("~\\Scripts\\File1.js")));

sb.Append(System.IO.File.ReadAllText(
       HttpContext.Current.Server.MapPath("~\\Scripts\\File2.js")));

var TheFile = sb.ToString();

Now I want to save this sb in the \Script directory in file called MyFile.js. I see several methods available but I'm not sure which one to choose.

How do I do this?

Thanks.

Upvotes: 3

Views: 4600

Answers (3)

Despertar
Despertar

Reputation: 22362

Server.MapPath() does not read in the file, it simply gives you the correct absolute path based on the relative path of your server. If you want to read in the files and write them to a single file, then try something like this,

string filenameA = HttpContext.Current.Server.MapPath("~\\Scripts\\File1.js"));
string filenameB = HttpContext.Current.Server.MapPath("~\\Scripts\\File2.js"));

string fileContentA = File.ReadAllText(filenameA);
string fileContentB - Flie.ReadAllText(filenameB);

System.IO.File.WriteAllText("filename", fileContentA + "\n" + fileContentB);

Now if you had many files to append together then using a StringBulider would be the way to go to improve performance.

StringBuilder sb = new StringBuilder();
foreach (string filename in filenames)
    sb.AppendLine(File.ReadAllText(filename));

File.WriteAllText(sb.ToString());

Furthermore, If the files are quite large and will not fit into memory, you can use FileStreams to just stream from the source and append to a master file.

foreach (string filename in filenames)
{
     using (FileStream srcFile = new FileStream(filename, FileMode.Open, FileAccess.Read))
     using (FileStream desFile = new FileStream(targetFilename, FileMode.Append, FileAccess.Write))
           srcFile.CopyTo(desFile);
}

Upvotes: 3

James
James

Reputation: 2841

Here you go:

File.WriteAllText(HttpContext.Current.Server.MapPath("~\\Scripts\\MyFile.js"), sb.ToString());

Upvotes: 1

Habib Zare
Habib Zare

Reputation: 1204

This code can help you:

using (System.IO.StreamWriter file = new   
System.IO.StreamWriter("\\Script\\ MyFile.js"))
        {

                    file.WriteLine(sb.ToString());

        }

Upvotes: 1

Related Questions