System.IO.DirectoryNotFoundException: 无法从远程服务器找到部分路径
System.IO.DirectoryNotFoundException: Could not find a part of the path from remote server
我允许用户上传包含图像路径的 excel 文件。问题是它抛出以下错误:
System.IO.DirectoryNotFoundException: Could not find a part of the
path 'C:\Users\gwphi_000\Desktop\test\OrderEmail.png'. at
System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at
System.IO.FileStream.Init(String path, FileMode mode, FileAccess
access, Int32 rights, Boolean useRights, FileShare share, Int32
bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String
msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess
access, FileShare share, Int32 bufferSize, FileOptions options, String
msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.File.InternalReadAllBytes(String path, Boolean checkHost)
at UploadExelFiles.Helpers.GetExcelDataFromFile.ReadExcelFile(String
pathToMedia)
在 IIS 中,我已将应用程序池更改为网络服务,在我的本地测试机器上工作正常,但在远程服务器上时它会抛出错误。
我的密码是
foreach (var item in excelList)
{
string fileName = Guid.NewGuid().ToString();
var content = contentService.CreateContent(item.Product, allEventsNode.Id, "accessorieItems");
IMediaService mediaService = ApplicationContext.Current.Services.MediaService;
var newImage = mediaService.CreateMedia($"{fileName}.jpeg", -1, "Image");
byte[] buffer = File.ReadAllBytes(Path.GetFullPath(item.ProductUrl));
MemoryStream strm = new MemoryStream(buffer);
newImage.SetValue("umbracoFile", $"{fileName}.jpeg", strm);
mediaService.Save(newImage);
var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
var image = umbracoHelper.Media(newImage.Id).Url;
string imagePath = image.ToString();
content.SetValue("productId", item.ProductId);
content.SetValue("productTitle", item.Product);
content.SetValue("productPrice", item.Price);
content.SetValue("productImage", imagePath);
content.SetValue("productDescription", item.ProductDescription);
contentService.SaveAndPublishWithStatus(content);
}
找不到该文件,因为它不存在,或者它没有权限。你说:
In IIS I have changed the app pool to Network Services and on my local
testing machine
但是你在服务器上做了同样的事情吗?
此外,请记住,当 运行 在服务器上时,它会查找服务器上的文件。服务器上是否存在路径 C:\Users\gwphi_000\Desktop\test\
?
以防万一其他人需要上传包含图像路径的 excel 文件,我已经发布了我是如何做到的。
重点是'Gabriel Luci'写的,路径是找服务器上的图片,怪我懒得不去想
无论如何,代码现在已被重写,因此您现在必须上传一个 zip 文件,该文件中包含 excel 文件和图像。
下面是如何从excel文件中获取数据的代码,请注意,这是针对Umbraco的,因此您可能需要修改它以供您自己使用。
public static bool ReadExcelFile(string pathToMedia)
{
try
{
string filePath = pathToMedia;
string zipFilePath = HttpContext.Current.Server.MapPath("~/www/UploadExcelFile");
string extractImagesTo = HttpContext.Current.Server.MapPath("~/www/Images/AccessoriesZipImages");
string pathToExcelFileOnServer = string.Empty;
using (ZipArchive archive = ZipFile.OpenRead(filePath))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
if (entry.FullName.EndsWith(".xlsx", StringComparison.OrdinalIgnoreCase) ||entry.FullName.EndsWith("xls", StringComparison.OrdinalIgnoreCase))
{
if (File.Exists(Path.Combine(zipFilePath, entry.Name)))
{
File.Delete(Path.Combine(zipFilePath, entry.Name));
}
pathToExcelFileOnServer = Path.Combine(zipFilePath, entry.Name);
entry.ExtractToFile(Path.Combine(zipFilePath, entry.Name));
}
}
}
using (ZipArchive archive = ZipFile.OpenRead(filePath))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
if (File.Exists(Path.Combine(extractImagesTo, entry.Name)))
{
File.Delete(Path.Combine(extractImagesTo, entry.Name));
}
if (entry.FullName.EndsWith(".png", StringComparison.OrdinalIgnoreCase) || entry.FullName.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase))
{
entry.ExtractToFile(Path.Combine(extractImagesTo, entry.Name));
}
}
}
if (!string.IsNullOrEmpty(pathToExcelFileOnServer))
{
using (var stream = File.Open(pathToExcelFileOnServer, FileMode.Open, FileAccess.Read))
{
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
var result = reader.AsDataSet();
List<ShoppingCartViewModel> excelList = new List<ShoppingCartViewModel>();
foreach (DataTable table in result.Tables)
{
foreach (DataRow dr in table.Rows.Cast<DataRow>().Skip(1)) //Skipping header
{
//Cannot seem to use cell names, so use cell location
excelList.Add(new ShoppingCartViewModel(dr[0].ToString(), dr[1].ToString(), dr[2].ToString(), Path.Combine(extractImagesTo, dr[3].ToString()), dr[4].ToString(), null, 0.00, null));
}
}
var contentService = ApplicationContext.Current.Services.ContentService;
var allEventsNode = ExcelUploadUmbracoAssignedContentHelper.HomePageContent();
int rootId = allEventsNode.Id;
var itemsForSale = contentService.GetChildren(rootId).Where(x => x.ContentType.Alias == "accessorieItems").ToList();
//Delete all current nodes
foreach (var items in itemsForSale)
{
contentService.Delete(items);
}
foreach (var item in excelList)
{
string fileName = Guid.NewGuid().ToString();
var content = contentService.CreateContent(item.Product, allEventsNode.Id,"accessorieItems");
IMediaService mediaService = ApplicationContext.Current.Services.MediaService;
var newImage = mediaService.CreateMedia($"{fileName}.jpeg", -1, "Image");
byte[] buffer = File.ReadAllBytes(Path.GetFullPath(item.ProductUrl));
MemoryStream strm = new MemoryStream(buffer);
newImage.SetValue("umbracoFile", $"{fileName}.jpeg", strm);
mediaService.Save(newImage);
var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
var image = umbracoHelper.Media(newImage.Id).Url;
string imagePath = image.ToString();
content.SetValue("productId", item.ProductId);
content.SetValue("productTitle", item.Product);
content.SetValue("productPrice", item.Price);
content.SetValue("productImage", imagePath);
content.SetValue("productDescription", item.ProductDescription);
contentService.SaveAndPublishWithStatus(content);
}
contentService.RePublishAll();
library.RefreshContent();
Array.ForEach(Directory.GetFiles(extractImagesTo), File.Delete);
//Delete empty folders in media folder
DeleteEmptyFolder.DeleteFolder();
}
}
}
return true;
}
catch (Exception ex)
{
throw new ApplicationException(ex.ToString());
}
}
我允许用户上传包含图像路径的 excel 文件。问题是它抛出以下错误:
System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Users\gwphi_000\Desktop\test\OrderEmail.png'. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) at System.IO.File.InternalReadAllBytes(String path, Boolean checkHost) at UploadExelFiles.Helpers.GetExcelDataFromFile.ReadExcelFile(String pathToMedia)
在 IIS 中,我已将应用程序池更改为网络服务,在我的本地测试机器上工作正常,但在远程服务器上时它会抛出错误。
我的密码是
foreach (var item in excelList)
{
string fileName = Guid.NewGuid().ToString();
var content = contentService.CreateContent(item.Product, allEventsNode.Id, "accessorieItems");
IMediaService mediaService = ApplicationContext.Current.Services.MediaService;
var newImage = mediaService.CreateMedia($"{fileName}.jpeg", -1, "Image");
byte[] buffer = File.ReadAllBytes(Path.GetFullPath(item.ProductUrl));
MemoryStream strm = new MemoryStream(buffer);
newImage.SetValue("umbracoFile", $"{fileName}.jpeg", strm);
mediaService.Save(newImage);
var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
var image = umbracoHelper.Media(newImage.Id).Url;
string imagePath = image.ToString();
content.SetValue("productId", item.ProductId);
content.SetValue("productTitle", item.Product);
content.SetValue("productPrice", item.Price);
content.SetValue("productImage", imagePath);
content.SetValue("productDescription", item.ProductDescription);
contentService.SaveAndPublishWithStatus(content);
}
找不到该文件,因为它不存在,或者它没有权限。你说:
In IIS I have changed the app pool to Network Services and on my local testing machine
但是你在服务器上做了同样的事情吗?
此外,请记住,当 运行 在服务器上时,它会查找服务器上的文件。服务器上是否存在路径 C:\Users\gwphi_000\Desktop\test\
?
以防万一其他人需要上传包含图像路径的 excel 文件,我已经发布了我是如何做到的。
重点是'Gabriel Luci'写的,路径是找服务器上的图片,怪我懒得不去想
无论如何,代码现在已被重写,因此您现在必须上传一个 zip 文件,该文件中包含 excel 文件和图像。
下面是如何从excel文件中获取数据的代码,请注意,这是针对Umbraco的,因此您可能需要修改它以供您自己使用。
public static bool ReadExcelFile(string pathToMedia)
{
try
{
string filePath = pathToMedia;
string zipFilePath = HttpContext.Current.Server.MapPath("~/www/UploadExcelFile");
string extractImagesTo = HttpContext.Current.Server.MapPath("~/www/Images/AccessoriesZipImages");
string pathToExcelFileOnServer = string.Empty;
using (ZipArchive archive = ZipFile.OpenRead(filePath))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
if (entry.FullName.EndsWith(".xlsx", StringComparison.OrdinalIgnoreCase) ||entry.FullName.EndsWith("xls", StringComparison.OrdinalIgnoreCase))
{
if (File.Exists(Path.Combine(zipFilePath, entry.Name)))
{
File.Delete(Path.Combine(zipFilePath, entry.Name));
}
pathToExcelFileOnServer = Path.Combine(zipFilePath, entry.Name);
entry.ExtractToFile(Path.Combine(zipFilePath, entry.Name));
}
}
}
using (ZipArchive archive = ZipFile.OpenRead(filePath))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
if (File.Exists(Path.Combine(extractImagesTo, entry.Name)))
{
File.Delete(Path.Combine(extractImagesTo, entry.Name));
}
if (entry.FullName.EndsWith(".png", StringComparison.OrdinalIgnoreCase) || entry.FullName.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase))
{
entry.ExtractToFile(Path.Combine(extractImagesTo, entry.Name));
}
}
}
if (!string.IsNullOrEmpty(pathToExcelFileOnServer))
{
using (var stream = File.Open(pathToExcelFileOnServer, FileMode.Open, FileAccess.Read))
{
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
var result = reader.AsDataSet();
List<ShoppingCartViewModel> excelList = new List<ShoppingCartViewModel>();
foreach (DataTable table in result.Tables)
{
foreach (DataRow dr in table.Rows.Cast<DataRow>().Skip(1)) //Skipping header
{
//Cannot seem to use cell names, so use cell location
excelList.Add(new ShoppingCartViewModel(dr[0].ToString(), dr[1].ToString(), dr[2].ToString(), Path.Combine(extractImagesTo, dr[3].ToString()), dr[4].ToString(), null, 0.00, null));
}
}
var contentService = ApplicationContext.Current.Services.ContentService;
var allEventsNode = ExcelUploadUmbracoAssignedContentHelper.HomePageContent();
int rootId = allEventsNode.Id;
var itemsForSale = contentService.GetChildren(rootId).Where(x => x.ContentType.Alias == "accessorieItems").ToList();
//Delete all current nodes
foreach (var items in itemsForSale)
{
contentService.Delete(items);
}
foreach (var item in excelList)
{
string fileName = Guid.NewGuid().ToString();
var content = contentService.CreateContent(item.Product, allEventsNode.Id,"accessorieItems");
IMediaService mediaService = ApplicationContext.Current.Services.MediaService;
var newImage = mediaService.CreateMedia($"{fileName}.jpeg", -1, "Image");
byte[] buffer = File.ReadAllBytes(Path.GetFullPath(item.ProductUrl));
MemoryStream strm = new MemoryStream(buffer);
newImage.SetValue("umbracoFile", $"{fileName}.jpeg", strm);
mediaService.Save(newImage);
var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
var image = umbracoHelper.Media(newImage.Id).Url;
string imagePath = image.ToString();
content.SetValue("productId", item.ProductId);
content.SetValue("productTitle", item.Product);
content.SetValue("productPrice", item.Price);
content.SetValue("productImage", imagePath);
content.SetValue("productDescription", item.ProductDescription);
contentService.SaveAndPublishWithStatus(content);
}
contentService.RePublishAll();
library.RefreshContent();
Array.ForEach(Directory.GetFiles(extractImagesTo), File.Delete);
//Delete empty folders in media folder
DeleteEmptyFolder.DeleteFolder();
}
}
}
return true;
}
catch (Exception ex)
{
throw new ApplicationException(ex.ToString());
}
}