[英]Xamarin Android System.IO.FileNotFoundException: Could not find file Exception
[英]System.IO.FileNotFoundException : Could not find file
我正在使用文件上傳控件。 但是,當我嘗試讀取上傳的文件時,它正在尋找創建項目的文件夾並給出錯誤信息。 此代碼
<input type="file" name="file" />
<button type="submit">Upload File</button>
和
[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();
}
}
}
在表單操作中使用enctype = "multipart/form-data"
。 您可以使用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>
}
源代碼查看示例在這里
在控制器內部,您可以使用如下方法的控制器:
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");
}
源代碼控制器示例在這里
這應該正常工作
如果您嘗試使用流讀取上傳的文件,則可以使用以下內容,
string result;
if (file != null && file.Length != 0)
{
using (var reader = new StreamReader(file.OpenReadStream()))
{
result = reader.ReadToEnd();
}
}
或者,如果您嘗試將上傳的文件保存在服務器中的某個位置,則應使用CopyTo方法,如下例所示,
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.