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



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的项目中时,所有引用都可以找到。

但我正在考虑创建一个实用程序类来处理所有此类操作。 所以我创建了一个类库项目并添加了一个类 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但我怀疑这是否正确?

但是,如何在没有任何开销的情况下满足我的需求呢?内存分配,执行和所有这些都非常关键

一旦确保控制器方法正确接收发布的文件引用,请阅读此答案。

无需在类库中添加System.Web引用。而只是将文件内容传递给重构的方法。此外,由于您正在创建一个实用程序类,请确保它可以返回任何类型的 DTO,而不仅仅是CustomerDTO。例如,如果您需要传入帐户文件并从中获取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);
}

在控制器中使用StreamReader读取文件内容不需要重构。这是不必要的IMO。

最新更新