创建并保存文件到目录中。

3

我正在使用字符串生成器从目录中读取多个文件,代码如下:

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

现在我想把这个sb保存到名为MyFile.js的文件中的\Script目录中。我看到有几种可用的方法,但我不确定该选择哪一种。

我该怎么做?

谢谢。

3个回答

3

Server.MapPath() 方法并不会读取文件,它只会根据服务器的相对路径为您提供正确的绝对路径。如果您想读取文件并将它们写入单个文件中,请尝试类似于以下代码的方法:

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

如果你需要将多个文件合并在一起,使用StringBuilder可以提高性能。

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

File.WriteAllText(sb.ToString());

此外,如果文件很大而且无法放入内存,您可以使用FileStream从源中进行流式传输并附加到主文件。
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);
}

1

这段代码可以帮助你:

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

                    file.WriteLine(sb.ToString());

        }

1

请看这里:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接