如何在类库项目中编写文件处理操作

时间:2017-07-29 06:52:54

标签: c# asp.net asp.net-mvc httppostedfilebase httppostedfile

UI

<input type = "file" title="Please upload some file" name="file" />

MVC

/*below method is called from a MVC controller 
 this method resides for now in MVC project itself*/
public IEnumerable<CustomerTO> FetchJson(HttpPostedFile file)
    {
        using (StreamReader sr = new StreamReader(file.FileName))
        {
            {
                file.saveAs("details.txt");
                string json = sr.ReadToEnd();
                IEnumerable<CustomerTO> customers=
                    JsonConvert.DeserializeObject<List<CustomerTO>>(json);
               return customers; 
            }
        }
    }

当MVC项目中的上述方法或某种基于Web的项目时,所有引用都可以找到。

但我想创建一个实用程序类来处理所有这些操作。 所以我创建了一个类库项目&amp;添加了一个类Utitlity.cs

班级图书馆

public IEnumerable<CustomerTO> FetchJson(HttpPostedFile file)
    {
        //but HttpPostedFile is throwing error.
        //NOTE Ideally,I shouldn't be saving the posted file
    }

现在我知道FileUpload是UI控件HttpPostedFile处理与此相关的所有操作。

我可以轻松添加引用using System.Web,但我怀疑这是否正确?

但是如何在没有任何开销的情况下解决我的要求呢? 内存分配,执行&amp;所有这些都非常关键

1 个答案:

答案 0 :(得分:1)

确保控制器方法正确接收发布的文件参考后,请阅读此答案。

您不需要在类库中添加System.Web引用。而只是将文件内容传递给重构方法。此外,由于您正在创建实用程序类,请确保它可以返回任何类型的DTO,而不仅仅是CustomerDTO。例如,如果您需要传入Accounts文件并从中获取AccountDTO,则应该能够使用相同的类/方法。

实际上,您应该能够使用该代码将任何字符串内容反序列化为您想要的任何类型。你可以在这里使用Generics

// Controller.cs
public IEnumerable<CustomerTO> FetchJson(HttpPostedFile file) 
{
    string fileContent;
    using (StreamReader sr = new StreamReader(file.FileName)) {
        file.saveAs("details.txt");
        fileContent = sr.ReadToEnd();
    }

    var customers = JsonSerializer.Deserialize<List<CustomerTO>>(content); // Refactored

    return customers; 
}

// JsonSerializer.cs
public static T Deserialize<T>(string content) {
    // ...
    return JsonConvert.DeserializeObject<T>(content);
}

使用Controller中的StreamReader读取文件内容无需重构。这是不必要的IMO。