【问题标题】:ASP.NET Save file InputStream [duplicate]ASP.NET 保存文件 InputStream [重复]
【发布时间】:2018-04-13 14:01:18
【问题描述】:

我正在尝试将文件上传到 ASP.NET 中的文件夹,到目前为止,我已经得到了这样的文件流:

public void Upload()
        {
            foreach (string file in Request.Files)
            {
                var fileContent = Request.Files[file];
                if (fileContent != null && fileContent.ContentLength > 0)
                {
                    var stream = fileContent.InputStream;
                    var fileName = fileContent.FileName;
                    //you can do anything you want here
                }
            }

            foreach (string key in Request.Form)
            {
                var value = Request.Form[key];
            }
        }

我只是不知道如何保存它....我太累了。

【问题讨论】:

  • 保存到哪里?..

标签: c# asp.net


【解决方案1】:

你试过 StreamWriter 吗?

using (StreamWriter sw = new StreamWriter(Server.MapPath("~/yourfile.txt"), true))
 {
     sw.WriteLine("lalala");
 }  

【讨论】:

    【解决方案2】:

    如果您使用.Net 4 及以上版本,则可以使用Stream.CopyTo 方法

    // Create the streams.
    MemoryStream destination = new MemoryStream();
    
    using (FileStream source = File.Open(@"c:\temp\data.dat",
        FileMode.Open))
    {
    
        Console.WriteLine("Source length: {0}", source.Length.ToString());
    
        // Copy source to destination.
        source.CopyTo(destination);
    }
    

    您可以在下面的代码中使用它

    public void Upload()
    {
        foreach (string file in Request.Files)
        {
            var fileContent = Request.Files[file];
            if (fileContent != null && fileContent.ContentLength > 0)
            {
                var stream = fileContent.InputStream;
                var fileName = fileContent.FileName;
                //you can do anything you want here
                var path = Server.MapPath("~/SomeFolder")
                using (var newFile = File.Create(Path.Combine(path,fileName))
                {
                    await stream.CopyTo(newFile);
                }
            }
        }
    
        foreach (string key in Request.Form)
        {
            var value = Request.Form[key];
        }
    }
    

    【讨论】:

      【解决方案3】:

      只需创建文件并从源流复制到目标流。

      using (var file = File.Create(fileName))
      {
          await stream.CopyToAsync(file);
      }
      

      【讨论】:

        猜你喜欢
        • 2016-12-22
        • 2021-06-12
        • 1970-01-01
        • 2011-05-22
        • 2021-10-03
        • 2016-12-22
        • 1970-01-01
        • 2011-12-04
        • 1970-01-01
        相关资源
        最近更新 更多