Frage

I have this code in my Web API app to write to a CSV file:

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);
    }
}

On the dev machine, the csv file is saved to "C:\Program Files (x86)\IIS Express" by default. In preparation for when it is deployed to its final resting/working place, what do I need to do to get the file to save, e.g., to the server's "Platypi" folder - anything special? Do I have to specifically set certain folder persimmons to allow writing to "Platypi."

Is it simply a matter of changing this line:

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

...to this:

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

?

War es hilfreich?

Lösung

In the case of the IIS folder the application has rights to write in there. I suggest to write files to the App_Data folder.

When you want to save files outside the IIS application folder you have to give the service account of the IIS application pool (I think it by default is NETWORKSERVICE) the appropriate rights on that folder.

As requested by B. Clay Shannon my implementation:

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

Andere Tipps

Thanks to Patrick Hofman; this is the exact code I am using, and it is saved to the project's App_Data folder:

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);
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top