我目前正在使用 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/