我可以从运行在其上的Web API应用程序将文件写入服务器计算机上的文件夹吗?

我在我的Web API应用程序中使用此代码来写入CSV文件:

private void SaveToCSV(InventoryItem invItem, string dbContext) { string csvHeader = "id,pack_size,description,vendor_id,department,subdepartment,unit_cost,unit_list,open_qty,UPC_code,UPC_pack_size,vendor_item,crv_id"; int dbContextAsInt = 0; int.TryParse(dbContext, out dbContextAsInt); string csvFilename = string.Format("Platypus{0}.csv", dbContextAsInt); string csv = string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12}", invItem.ID, invItem.pksize, invItem.Description, invItem.vendor_id, invItem.dept, invItem.subdept, invItem.UnitCost, invItem.UnitList, invItem.OpenQty, invItem.UPC, invItem.upc_pack_size, invItem.vendor_item, invItem.crv_id); string existingContents; using (StreamReader sr = new StreamReader(csvFilename)) { existingContents = sr.ReadToEnd(); } using (StreamWriter writetext = File.AppendText(csvFilename)) { if (!existingContents.Contains(csvHeader)) { writetext.WriteLine(csvHeader); } writetext.WriteLine(csv); } } 

在开发机器上,默认情况下,csv文件保存为“C:\ Program Files(x86)\ IIS Express”。 为了准备将它部署到最终的rest/工作场所,我需要做些什么来保存文件,例如,到服务器的“Platypi”文件夹 – 什么特别的? 我是否必须专门设置某些文件夹柿子才能写入“Platypi”。

这只是改变这条线的问题:

 string csvFilename = string.Format("Platypus{0}.csv", dbContextAsInt); 

……对此:

 string csvFilename = string.Format(@"\Platypi\Platypus{0}.csv", dbContextAsInt); 

在IIS文件夹的情况下,应用程序有权在那里写入。 我建议将文件写入App_Data文件夹。

如果要将文件保存在IIS应用程序文件夹之外,则必须为该应用程序池(我认为默认情况下为NETWORKSERVICE)提供该文件夹的相应权限。

按照B. Clay Shannon的要求,我的实施:

 string fullSavePath = HttpContext.Current.Server.MapPath(string.Format("~/App_Data/Platypus{0}.csv", dbContextAsInt)); 

感谢Patrick Hofman; 这是我正在使用的确切代码,它保存到项目的App_Data文件夹中:

 public static string appDataFolder = HttpContext.Current.Server.MapPath("~/App_Data/"); . . . string csvFilename = string.Format("Platypus{0}.csv", dbContextAsInt); string fullSavePath = string.Format("{0}{1}", appDataFolder, csvFilename);