【问题标题】:Can I write a file to a folder on a server machine from a Web API app running on it?我可以从服务器上运行的 Web API 应用程序将文件写入服务器计算机上的文件夹吗?
【发布时间】:2014-03-05 13:19:17
【问题描述】:

我的 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”。为了准备将其部署到最终的休息/工作地点,我需要做些什么来保存文件,例如,保存到服务器的“Platypi”文件夹 - 有什么特别的吗?我是否必须专门设置某些文件夹柿子以允许写入“Platypi”。

是否只是换行的问题:

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

...到这个:

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

?

【问题讨论】:

    标签: c# asp.net-web-api file-permissions streamwriter file-processing


    【解决方案1】:

    对于 IIS 文件夹,应用程序有权在其中写入。我建议将文件写入 App_Data 文件夹。

    当您想将文件保存在 IIS 应用程序文件夹之外时,您必须授予 IIS 应用程序池的服务帐户(我认为默认情况下是 NETWORKSERVICE)对该文件夹的适当权限。

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

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

    【讨论】:

    • 我会通过 Environment.SpecialFolder.ApplicationData 写入 AppData 文件夹吗?
    • 下面一行只返回字符串“ApplicationPath”:string pathOfMostResistence = Environment.SpecialFolder.ApplicationData.ToString();
    • 只需使用Server.MapPath("~/App_Data/...")。这将返回 app_data 文件夹。 ~ 表示应用程序根文件夹。
    • 您需要更多帮助吗?
    • 试图看看这会返回什么,我添加了以下代码: string bla = Server.MapPath("~/App_Data/"); ...并且“服务器”无法识别(“无法解析符号“服务器””)
    【解决方案2】:

    感谢帕特里克霍夫曼;这是我正在使用的确切代码,它被保存到项目的 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);
    

    【讨论】:

      猜你喜欢
      • 2012-05-05
      • 1970-01-01
      • 2013-05-21
      • 1970-01-01
      • 2017-08-01
      • 2013-08-21
      • 2011-01-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多