How to write file handling operations in class library project

798 Views Asked by At

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; 
            }
        }
    }

When the above method in MVC project or some kind of web based project, all references are find fine.

But I am thinking to create a utility class to handle all such operations. So I created a class library project & added a class Utitlity.cs

Class Library

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

Now I know FileUpload is UI control HttpPostedFile handles all operations related to this.

I can easily add reference using System.Web but I doubt if that's right??

But how do I address my requirement then without any kind of overhead?? Memory allocation, execution & all such is very critical

1

There are 1 best solutions below

3
On

Read this answer once you make sure that controller method receives posted file reference properly.

You don't need to add System.Web reference in class library. Instead just pass file contents to refactored method. Moreover since you are making a utility class, make sure it can return any type of DTO and not just CustomerDTO. You should be able to use the same class/ method, if you ever need to pass in Accounts file and get AccountDTOs out of it, for example.

In fact, you should be able to use that code for deserializing any string content to any type you want. You could use Generics here.

// 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);
}

Reading file content using StreamReader in Controller need not be refactored. That's unnecessary IMO.