I can write data to the App_Data folder in my ASP.NET Web API app like so:
string appDataFolder = HttpContext.Current.Server.MapPath("~/App_Data/");
var htmlStr = // method that returns html as a string
string htmlFilename = "platypus.html";
string fullPath = Path.Combine(appDataFolder, htmlFilename);
File.WriteAllText(fullPath, htmlStr);
I want to do something similar in an ASP.NET MVC app (the data is different - a PDF file instead of an html file), but "File" is not recognized. I try this:
using (var ms = new MemoryStream())
. . .
var bytes = ms.ToArray();
string appDataFolder = AppDomain.CurrentDomain.GetData("DataDirectory").ToString();
string pdfFilename = "test.pdf";
string fullPath = Path.Combine(appDataFolder, pdfFilename);
File.WriteAllText(fullPath, bytes);
...but get, "'System.Web.Mvc.Controller.File(byte[], string)' is a 'method', which is not valid in the given context'"
In the first place, I don't think my code is what the err msg seems to indicate it is, but nevertheless it's not accepted, so: how can I write data to the App_Data folder in ASP.NET MVC?
It looks like a namespace collision. The compiler is grabbing File
from a different namespace than is expected. The File
class that should make this work is in the System.IO
namespace and not the System.Web.Mvc.Controller
namespace.
This can be fixed by explicitly specifying the correct namespace when calling File.WriteAllText()
:
System.IO.File.WriteAllText(fullPath, bytes);