如何在asp.net mvc中读取上传文件的内容

时间:2018-02-08 23:53:16

标签: c# asp.net-mvc

您好我想阅读上传文件的文字。上传的文件是.txt文件。出于某种原因,contents始终为空字符串。

[HttpPost]
public ActionResult Upload(HttpPostedFileBase upload)
{
    string contents = new StreamReader(upload.InputStream).ReadToEnd();
}

html:

<form action="/Document/Upload" method="post" enctype="multipart/form-data">
    @Html.AntiForgeryToken()
    <input class="" accept=".txt" type="file" name="uf" required />
</form>

1 个答案:

答案 0 :(得分:0)

您可能希望确保输入流重置为第一位。我通常会将文件读入内存流,首先:

string contents = string.Empty;

using (var ms = new System.IO.MemoryStream())
{
    upload.InputStream.CopyTo(ms);
    ms.Position = 0;

    contents = new StreamReader(ms).ReadToEnd();
}

否则,只需重置索引即可:

upload.InputStream.Position = 0;

string contents = new StreamReader(upload.InputStream).ReadToEnd();