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

B. *_*non 9 c# file-permissions streamwriter file-processing asp.net-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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

string csvFilename = string.Format("Platypus{0}.csv", dbContextAsInt);
Run Code Online (Sandbox Code Playgroud)

......对此:

string csvFilename = string.Format(@"\Platypi\Platypus{0}.csv", dbContextAsInt);
Run Code Online (Sandbox Code Playgroud)

Pat*_*man 15

对于IIS文件夹,应用程序有权在那里写入.我建议将文件写入App_Data文件夹.

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

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

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

  • 只需使用`Server.MapPath("〜/ App_Data/...")`.这将返回app_data文件夹.`~`表示应用程序根文件夹. (2认同)