c# - 如何在网络位置写入 .csv 文件?

标签 c# file asp.net-mvc-4 csv export-to-csv

我目前正在使用 Response 对象将 .csv 文件写入客户端浏览器,这过去/现在是一项相当容易的工作。

但现在要求已更改为在网络位置创建此文件,作业可以随时从该位置选择它。

我不确定如何实现这一目标,任何建议都会有所帮助。

现有代码:

Response.ClearContent();
Response.AddHeader("content-disposition", "attachment;filename=" + GenerateFileName(publishToViewModel[0].ProjectId));
Response.ContentType = "text/csv";
StreamWriter writer = new StreamWriter();
try
{
    string CSVFriendlyData = this.GetCSV(publishToViewModel);
    writer.Write(CSVFriendlyData);
    Response.Write(writer.ToString());
    Response.End();
}

最佳答案

因为很难保证对网络文件的写入会成功(您的旧文件可能仍然存在,并且定时作业可能锁定了它,等等)建立一个机制是个好主意将多次重试写入文件。

void WriteToNetworkFile()
{
  int retries = 3;    
  while(retries > 0)
  {
     if(tryWriteFile())
     {
        break;
     } 
     retries--;

     // you could add a timeout here to make sure your attempts are a little more
     //spaced out.
     //it could be in the form of a Thread.Sleep, or you could extract a method and
     //call it using a timer.

     if(retries < 1)
     {
        //log that we failed to write the file and gave up on trying.
     }
  }
}    
protected void tryWriteFile()
{
   try
   {
     //you could pass this path as a parameter too.
     var fileLoc = "\\server\folder\file.ext";

     //open and obtain read/write lock on the file
     //using FileMode.CreateNew will ensure that a new file is created.
     //alternatively, you can use FileMosw.Create to create a new file
     //or overwrite the old file if it is there.
     using (var fs = File.Open(fileLoc, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None))
     {
          var sw = new StreamWriter(fs);
          sw.Write("file contents go here");
          sw.Flush();
          sw.Close();
          return true;
     }
    }
    catch(Exception e)
    {
       //you might want to log why the write failed here.
       return false;
    }
}

关于c# - 如何在网络位置写入 .csv 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32710460/

相关文章:

c# - 为什么在 C# 中使用泛型约束

swift - 如何创建用于写入的文本文件

asp.net-mvc-4 - ASP.Net MVC4 移动感知输出缓存

javascript - 如何从Jquery验证SignalR集线器

c# - Controller 操作中的异步等待 : Error: Can not await 'void'

c# - 如何使用 Rhino Mocks 模拟 MEF 导出?

c# - "override"枚举的最佳方法是什么?

c# - 有没有办法在调用之前检查操作是否有效?

android - 使用我的 Android 应用程序注册 FileExtension

python-2.7 - Scrapy从FTP下载文件