如何在网络位置上编写.csv文件

本文关键字:csv 文件 位置 网络 | 更新日期: 2023-09-27 18:13:57

我目前正在使用响应对象编写。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();
}

如何在网络位置上编写.csv文件

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

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