【问题标题】:System.IO.DirectoryNotFoundException: Could not find a part of the path from remote serverSystem.IO.DirectoryNotFoundException:找不到来自远程服务器的部分路径
【发布时间】:2018-06-28 17:47:12
【问题描述】:

我允许用户上传具有图像路径的 excel 文件。问题是它抛出以下错误:

System.IO.DirectoryNotFoundException:找不到一部分 路径“C:\Users\gwphi_000\Desktop\test\OrderEmail.png”。在 System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) 在 System.IO.FileStream.Init(String path, FileMode mode, FileAccess 访问、Int32 权限、布尔用户权限、FileShare 共享、Int32 bufferSize,FileOptions 选项,SECURITY_ATTRIBUTES secAttrs,字符串 msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) 在 System.IO.FileStream..ctor(字符串路径,FileMode 模式,FileAccess 访问、FileShare 共享、Int32 bufferSize、FileOptions 选项、字符串 msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) 在 System.IO.File.InternalReadAllBytes(字符串路径,布尔检查主机) 在 UploadExelFiles.Helpers.GetExcelDataFromFile.ReadExcelFile(字符串 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);
}

【问题讨论】:

  • 能否提供一个excel文件数据的例子?
  • 您正在尝试从服务器访问用户的文件系统,这就是您可能遇到此错误的原因。在本地,它允许您使用它的本地服务器,但远程机器不能这样做。

标签: c# umbraco7


【解决方案1】:

以防万一其他人需要上传包含图像路径的 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());
            }
        } 

【讨论】:

    【解决方案2】:

    它无法找到该文件,因为它不存在,或者它没有权限。你说:

    在 IIS 中,我已将应用程序池更改为网络服务,并在我的本地 试验机

    但是你在服务器上做了同样的事情吗?

    另外,请记住,在服务器上运行时,它会在服务器上查找文件。服务器上是否存在路径C:\Users\gwphi_000\Desktop\test\?

    【讨论】:

    • 嗨,Gabriel,这就是问题所在,如何更改在客户端计算机上查看的路径。路径是 C:\\Users\\gwphi_000\\Desktop\\test\\OrderEmail.png 我完全忘记了。
    • 在服务器上,您知道客户端的 IP 地址,因此您可以将 C: 替换为 \\[IP]\C$,假设您的组织中启用了管理 C$ 共享并且您的防火墙允许它。但是,您还必须使用在用户计算机上具有管理员权限的凭据运行它。它有很多部分会损坏。我建议找到另一种方法来做你需要的事情(直接在最终用户的计算机上运行)
    猜你喜欢
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-10
    相关资源
    最近更新 更多