[英]How to write a .csv file on a network location?
I am currently writing a .csv to client browser using Response object, which was/is a fairly easy job. 我目前正在使用Response对象将.csv编写到客户端浏览器,这是/非常简单的工作。
But now the requirement has been changed to create this file at a network location from where any time the job will pick it. 但是现在,更改了在网络位置创建该文件的要求,作业可以从该位置随时选择它。
I am not sure how can I achieve this, any suggestions would be helpful. 我不确定如何实现此目标,任何建议都会有所帮助。
Existing Code: 现有代码:
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();
}
since it is hard to guarantee that a write to a network file will be successful (your old file might still be there, and the timed job might have a lock on it, etc) it's a good idea to build a mechanism that will retry writing to the file several times. 因为很难保证成功写入网络文件(您的旧文件可能仍然存在,并且定时作业可能已锁定,等等),所以最好建立一种机制来重试写入文件多次。
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.