我使用FileStream.Create
将.csv文件上传到服务器上,然后将其读入SQL数据库。一旦读入,我只是从写入它的文件夹中删除该文件。目标是将文件放入数据库。这可以在本地运行正常,但我无法在新服务器上获得写访问权限,因此我得到UnauthorizedAccessException
。我不认为有必要将文件上传到服务器以将其读入SQL表,但我无法调整代码。
[HttpPost]
public ActionResult UploadValidationTable(HttpPostedFileBase csvFile)
{
var inputFileDescription = new CsvFileDescription
{
SeparatorChar = ',',
FirstLineHasColumnNames = true
};
var cc = new CsvContext();
var filePath = uploadFile(csvFile.InputStream);
var model = cc.Read<Credit>(filePath, inputFileDescription);
try
{
var entity = new Entities();
foreach (var item in model)
{
var tc = new TemporaryCsvUpload
{
Id = item.Id,
Amount = item.Amount,
Date = item.Date,
Number = item.Number,
ReasonId = item.ReasonId,
Notes = item.Notes
};
entity.TemporaryCsvUploads.Add(tc);
}
entity.SaveChanges();
System.IO.File.Delete(filePath);
这是uploadFile方法:
private string uploadFile(Stream serverFileStream)
{
const string directory = "~/Content/CSVUploads";
var directoryExists = Directory.Exists(Server.MapPath(directory));
if (!directoryExists)
{
Directory.CreateDirectory(Server.MapPath(directory));
}
var targetFolder = Server.MapPath(directory);
var filename = Path.Combine(targetFolder, Guid.NewGuid() + ".csv");
try
{
const int length = 256;
var buffer = new byte[length];
// write the required bytes
using (var fs = new FileStream(filename, FileMode.Create))
{
int bytesRead;
do
{
bytesRead = serverFileStream.Read(buffer, 0, length);
fs.Write(buffer, 0, bytesRead);
} while (bytesRead == length);
}
serverFileStream.Dispose();
return filename;
}
catch (Exception)
{
return string.Empty;
}
}
总结一下,我将.csv文件上传到临时位置,将其读入对象,将其读入数据库,然后从临时位置删除.csv文件。我正在使用Linq2Csv来创建对象。我可以在不将文件上传到服务器的情况下执行此操作(因为我无法获得写访问权限)吗?
答案 0 :(得分:0)
根据http://www.codeproject.com/Articles/25133/LINQ-to-CSV-library,
您可以从StreamReader中读取
Read<T>(StreamReader stream)
Read<T>(StreamReader stream, CsvFileDescription fileDescription)
你可以使用streamreader(或stringbuilder)创建你的文件而不是csv - Write StringBuilder to Stream
How to take a stringbuilder and convert it to a streamReader?
然后将其发送到您的CSVContext?