2016-02-24 2 views
1

Я создал оболочку (библиотеку классов) для COM вокруг библиотеки DotNetZip, которую я использую в приложении VB6. Я создал образец приложения, используя обертку на компьютере XP, и он отлично работает. Когда я создаю установщик и устанавливаю приложение на Windows Server 2008 R2, он не может читать zip-файлы с UNC-пути.DotNetZip сбой при чтении zip-файла из UNC-пути

Ниже мой C# код:

if (File.Exists(zipFileName)) 
{ 
    // check if the directory exists 
    if (Directory.Exists(extractionPath)) 
    { 
     // remove the directory 
     Directory.Delete(extractionPath, true); 
    } 

    // recreate the directory 
    Directory.CreateDirectory(extractionPath); 

    // unzip the files 
    using (ZipFile loZip = ZipFile.Read(zipFileName)) 
    { 
     // Add this line to fix an issue with the DLL 
     // http://dotnetzip.codeplex.com/workitem/14087 
     loZip.ParallelDeflateThreshold = -1; 

     loZip.ExtractAll(extractionPath, ExtractExistingFileAction.OverwriteSilently); 
    } 
} 
else 
{ 
    lsResult = "@@@Error - Zip file does not exist. "; 
} 

Файл Zip находится по следующему адресу (это локальная папка, совместно поэтому я использую путь UNC, но это может очень будет находиться в сетевой ресурс)

Zip File Name = '\\\\DEV-2012X\\1454444717051\\MB4.zip' 

Это сообщение об исключении:

Could not find file '\\DEV-2012X\1454444717051\MB4.zip'. 

и это трассировка стека

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) 
    at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share) 
    at Ionic.Zip.ZipFile.get_ReadStream() 
    at Ionic.Zip.ZipFile.ReadIntoInstance(ZipFile zf) 
    at Ionic.Zip.ZipFile.Read(String fileName, TextWriter statusMessageWriter, Encoding encoding, EventHandler`1 readProgress) 
    at Ionic.Zip.ZipFile.Read(String fileName) 
    at ZipUtility.Zip.UnZipAllContents(String zipFileName, String extractionPath) 

Я могу получить доступ к папке с этой машины без каких-либо проблем. Я также попытался использовать .net Impersonation на ссылке this, но это тоже не помогло.

Спасибо за глядя в этот

[EDIT - 1]

Это когда я пытаюсь передать поток методу чтения:

MemoryStream ms = new MemoryStream(); 

try 
{ 
    using (FileStream file = new FileStream(zipFileName, FileMode.Open, FileAccess.Read)) 
    { 
     byte[] bytes = new byte[file.Length]; 
     file.Read(bytes, 0, (int)file.Length); 
     ms.Write(bytes, 0, (int)file.Length); 
    } 
} 
catch (Exception ex) 
{ 
    lsResult = "Stream reading crashed. " + ex.Message + Environment.NewLine + Environment.NewLine + ex.InnerException + Environment.NewLine + Environment.NewLine + ex.StackTrace + Environment.NewLine + Environment.NewLine; 
} 

// unzip the files 
using (ZipFile loZip = ZipFile.Read(ms)) 
{ 
    // Add this line to fix an issue with the DLL 
    // http://dotnetzip.codeplex.com/workitem/14087 
    loZip.ParallelDeflateThreshold = -1; 

    loZip.ExtractAll(extractionPath, ExtractExistingFileAction.OverwriteSilently); 
} 

После это ошибка, Я получаю:

Stream reading crashed. Could not find file '\\DEV-2012X\SLWatch\Test Everything1454444717051\MB4.zip'. 

И стек след:

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) 
    at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access) 
    at ZipUtility.Zip.UnZipAllContents(String zipFileName, String extractionPath) 

[/ EDIT - 1]

[EDIT - 2]

Ниже приведены подписи для ZipFile.Читайте метод:

public static ZipFile Read(string fileName) 
public static ZipFile Read(System.IO.Stream zipStream) 
public static ZipFile Read(string fileName, ReadOptions options) 
public static ZipFile Read(System.IO.Stream zipStream, ReadOptions options) 

[/ EDIT - 2]

[EDIT - 3]

код, как он работает в настоящее время:

public string UnZipAllContents(string zipFileName, string extractionPath) 
{ 
    string lsResult = string.Empty; 
    string lsRemoteComputerName = string.Empty; 
    string lsStep = "1-"; 

    try 
    { 
     lsRemoteComputerName = Path.GetPathRoot(zipFileName); 
     lsStep += "2," + lsRemoteComputerName + "-"; 

     lsStep += "3-"; 
     using (UNCAccessWithCredentials unc = new UNCAccessWithCredentials()) 
     { 
      lsStep += "3.1-"; 
      bool lb = unc.NetUseWithCredentials(Path.GetPathRoot(zipFileName), 
              "Bhatti", 
              string.Empty, 
              "MyPassword"); 

      lsStep += "4, " + lb.ToString() + "-"; 

      string[] dirs = Directory.GetFiles(Path.GetPathRoot(zipFileName), "*",SearchOption.AllDirectories); 
      lsStep += "4.1,"; 
      foreach (string d in dirs) 
      { 
       lsStep += d + ","; 
      } 
      lsStep += "-"; 

      if (File.Exists(zipFileName)) 
      { 
       lsStep += "5-"; 
       // check if the directory exists 
       if (Directory.Exists(extractionPath)) 
       { 
        // remove the directory 
        Directory.Delete(extractionPath, true); 
       } 

       // recreate the directory 
       Directory.CreateDirectory(extractionPath); 

       lsStep += "6-"; 
       // unzip the files 
       using (ZipFile loZip = ZipFile.Read(zipFileName)) 
       { 
        lsStep += "7-"; 
        loZip.ExtractAll(extractionPath, ExtractExistingFileAction.OverwriteSilently); 
       } 
       lsStep += "8-"; 
      } 
      else 
      { 
       lsResult += "@@@Error - Zip file does not exist. " + lsStep; 
      } 
     } 
    } 
    catch (Exception loException) 
    { 
     lsResult += lsStep + Environment.NewLine + "@@@Error - " + loException.Message + Environment.NewLine + Environment.NewLine + loException.InnerException + Environment.NewLine + Environment.NewLine + loException.StackTrace; 
    } 

    return lsResult; 
} 

И это это журнал, который создается:

1-2,\\DEV-2012X\SLWatch-3-3.1-4, True-4.1,\\DEV-2012X\SLWatch\BW123.zip,\\DEV-2012X\SLWatch\1454444717051.xml,\\DEV-2012X\SLWatch\1454444717051\MB4.zip,-5-6- 

    @@@Error - Could not find file '\\DEV-2012X\SLWatch\1454444717051\MB4.zip'. 

    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) 
    at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share) 
    at Ionic.Zip.ZipFile.get_ReadStream() 
    at Ionic.Zip.ZipFile.ReadIntoInstance(ZipFile zf) 
    at Ionic.Zip.ZipFile.Read(String fileName, TextWriter statusMessageWriter, Encoding encoding, EventHandler`1 readProgress) 
    at Ionic.Zip.ZipFile.Read(String fileName) 
    at ZipUtility.Zip.UnZipAllContents(String zipFileName, String extractionPath) 

[/ EDIT - 3]

+0

вы можете передать поток файла вместо пути к zipfile.read? –

+1

Скорее всего, это ошибка разрешений. –

+0

@SteveWellens: Я дал полное разрешение «Все» на эту папку. – Bhatti

ответ

1

Ваша проблема с доступом к файлам и исключение является доказательством того, что

, потому что вы пытаетесь загрузить файл, чтобы в MemoryStream вы ловите FileNotFoundException но ваш код продолжает работать, поэтому вы получаете еще одну ошибку от DotNetZip из вашего пустого MemoryStream.

Ваш код должен выглядеть так:

MemoryStream ms = new MemoryStream(); 
bool success; 
try 
{  
    if(File.Exists(zipFileName)) 
    { 
     using (FileStream file = new FileStream(zipFileName, FileMode.Open, FileAccess.Read)) 
     { 
      byte[] bytes = new byte[file.Length]; 
      file.Read(bytes, 0, (int)file.Length); 
      ms.Write(bytes, 0, (int)file.Length); 
     } 


     // unzip the files 
     using (ZipFile loZip = ZipFile.Read(ms)) 
     { 
      // Add this line to fix an issue with the DLL 
      // http://dotnetzip.codeplex.com/workitem/14087 
      loZip.ParallelDeflateThreshold = -1; 

      loZip.ExtractAll(extractionPath, ExtractExistingFileAction.OverwriteSilently); 
     } 
     success = true; 
    } 
    else 
    { 
     lsResult = "ZipFile Not Found"; 
     success = false; 
    } 
} 
catch (Exception ex) 
{ 
     success = false; 
    lsResult = "Stream reading crashed. " + ex.Message + Environment.NewLine + Environment.NewLine + ex.InnerException + Environment.NewLine +  Environment.NewLine + ex.StackTrace + Environment.NewLine + Environment.NewLine; 
} 

[Редактировать] Проверьте это.

Check if directory exists on Network Drive [/ Edit]

+0

Я использую путь как «\\ DEV-2012X \ 1454444717051 \ MB4.zip», а DEV-2012X - это сервер, на котором я тестирую это. Да, я знаю, что код должен быть таким, но я просто добавил его быстро, чтобы проверить и обновить только исключение, которое я получаю от первого улова.Пути UNC - это кошмар – Bhatti

+0

Посмотрите эту ссылку и проверьте, будут ли они добавлены учетные данные, и она будет работать http://stackoverflow.com/questions/10214596/using-unc-path-with-credentials –

+0

попробовал это, но не повезло .. я вижу файл там через код, но функция ZipFile.Read по-прежнему падает с той же ошибкой. – Bhatti

Смежные вопросы