简体   繁体   English

如何在ASP.NET MVC中的文件中保存对象列表

[英]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. 我试图将对象列表(包含文件URI)保存到ASP.NET MVC中的文件中,以便在加载页面时,将加载并显示保存的文件URI。 When I tried it in Windows Forms, it works perfectly, however, I cannot get it working in MVC. 当我在Windows窗体中尝试它时,它可以完美运行,但是,我无法在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. 作为参考,以下是我在Windows Forms中使用的代码,用于将对象列表保存在文件中并加载文件的内容。

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: 当我将相同的代码放入Controller类时,在以下几行中出现错误:

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 'Controller.File(byte [],string)'是一个方法,在给定的上下文中无效

My controller name is "FilesController" but I don't think that it is conflicting the names. 我的控制器名称是“ FilesController”,但我不认为它与名称冲突。

Any help would be very appreciated! 任何帮助将不胜感激! :) Thank you very much! :) 非常感谢你!

'Controller.File(byte[], string)' is a method, which is not valid in the given context 'Controller.File(byte [],string)'是一个方法,在给定的上下文中无效

The Controller class has a member called File already . Controller具有一个名为File的成员 (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. 对该File的第一个引用是该方法,该方法使此行无效。 If you want to use the System.IO.File object, you have to specify that: 如果要使用System.IO.File对象,则必须指定:

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. 但是为简单起见,如果应用程序首先没有做很多事情,那么在控制器中执行这些操作并不少见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM