user2950895 user2950895 - 3 years ago 124
ASP.NET (C#) Question

How to save a list of objects in a file in ASP.NET MVC

I am trying to save a list of objects (containing files URI) to a file in ASP.NET MVC so that when I load the page, the saved files URI will be loaded and displayed. When I tried it in Windows Forms, it works perfectly, however, I cannot get it working in MVC.

As a reference, the following is the code which I am using in Windows Forms to save the list of objects in a file and to load the contents of the file.

private void Save(List<Uri> list)
{
BinaryFormatter b = new BinaryFormatter();
FileStream file = File.Create(fileName);
b.Serialize(file, list.ToList());
file.Close();
}

private void LoadFile()
{
try
{
BinaryFormatter b = new BinaryFormatter();
FileStream file = File.Open(fileName, FileMode.Open);
fileList = (List<Uri>)b.Deserialize(file);
file.Close();
}
catch
{
MessageBox.Show("Error Loading File!");
}
}


When I put the same code in the Controller class, I am getting an error in the following lines:

FileStream file = File.Create(fileName);

FileStream file = File.Open(fileName, FileMode.Open);


Error:

'Controller.File(byte[], string)' is a method, which is not valid in the given context

My controller name is "FilesController" but I don't think that it is conflicting the names.

Any help would be very appreciated! :)
Thank you very much!

Answer Source

'Controller.File(byte[], string)' is a method, which is not valid in the given context

The Controller class has a member called File already. (A method, as the error states.) So when you do this in your controller:

File.Create(fileName);

The first reference to something called File is that method, which makes this line invalid. If you want to use the System.IO.File object, you have to specify that:

System.IO.File.Create(fileName);

Ideally such dependency-based operations wouldn't happen in a controller. But for simplicity it's not entirely uncommon to do these in a controller if the app doesn't do much in the first place.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download