简体   繁体   中英

System.IO.FileNotFoundException : Could not find file

I am using file upload control. But when I try to read uploaded file, it's looking for folder where project is created and giving error. The code for this

 <input type="file" name="file" />
 <button type="submit">Upload File</button>

and

[HttpPost]
    public IActionResult UploadFile(IFormFile file)
    {
        string FileName = file.FileName;
        if (file != null && file.Length != 0)
        {
            FileStream fileStream = new FileStream(FileName, FileMode.Open);
            using (StreamReader streamReader = new StreamReader(fileStream))
            {
                string line = streamReader.ReadLine();
            }

        }
    }

Use enctype = "multipart/form-data" inside your form action. You can use razor @using (Html.BeginForm())

@using (Html.BeginForm("UploadFile", "YourController", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" name="file" />
    <button type="submit">Submit</button>
}

Source code view sample here

And inside your controller, you can use a method controller like this:

public async Task<IActionResult> UploadFile(IFormFile file)
{
    var uploadPath = Path.Combine(hostingEnv.WebRootPath, "uploadsfolder");

    using (var fileStream = new FileStream(Path.Combine(uploadPath, file.FileName), FileMode.Create))
    {
        await file.CopyToAsync(fileStream);
    }
    return RedirectToAction("Index");
 }

Source code controller sample here

This should work properly

If you are trying to read the uploaded file using stream, you can use the following,

        string result;
        if (file != null && file.Length != 0)
        {
            using (var reader = new StreamReader(file.OpenReadStream()))
            {
               result = reader.ReadToEnd();  
            }
        }

Or, if you are trying to save the uploaded file somewhere in the server then you should use the CopyTo method like below example,

        var destinationPath= Path.GetTempFileName(); //Change this line to point to your actual destination
        using (var stream = new FileStream(destinationPath, FileMode.Create))
        {
            await formFile.CopyToAsync(stream);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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