2013-01-24 270 views
2

時創建零件Uri我使用下面的代碼壓縮文件。我發現當被壓縮的路徑中的文件夾包含散列(#)時,CreatePartUri(uri)會拋出異常:當路徑包含#

零件URI不能包含片段組件。

由於我無法改變文件夾名稱,我該如何轉義路徑中的#符號才能正確創建Uri?

using System; 
using System.IO; 
using System.IO.Packaging; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string targetFilePath = "C:\\TEMP.ZIP"; 
      try 
      { 
       if (File.Exists(targetFilePath)) 
       { 
        File.Delete(targetFilePath); 
       } 
       string packageRelationshipType = 
         @"http://schemas.openxmlformats.org/" + 
         @"package/2007/relationships/htmx/root-html"; 

       CompressionOption compressionOption = CompressionOption.Maximum; 

       using (Package package = Package.Open(targetFilePath, 
                 FileMode.OpenOrCreate)) 
       { 
        string fileName = @"\#TestFolder\TestFile.txt"; 
        string filePathOnServer = @"C:\" + fileName; 

        Uri uri = new Uri(fileName, UriKind.Relative); 
        Uri partUriDocument = PackUriHelper.CreatePartUri(uri); 

        PackagePart packagePartDocument = 
            package.CreatePart(partUriDocument, 
           System.Net.Mime.MediaTypeNames.Text.RichText, 
           compressionOption); 

        using (FileStream fileStream = new FileStream 
                 (filePathOnServer, 
                 FileMode.Open, 
                 FileAccess.Read)) 
        { 
         CopyStream(fileStream, packagePartDocument.GetStream()); 
        } 

        package.CreateRelationship(packagePartDocument.Uri, 
               TargetMode.Internal, 
               packageRelationshipType); 
       } 
      } 
      catch (Exception e) 
      { 
       string exceptionText = e.ToString(); 
      } 
     } 
     private static void CopyStream(Stream source, Stream target) 
     { 
      const int bufSize = 0x1000; 
      byte[] buf = new byte[bufSize]; 
      int bytesRead = 0; 

      while ((bytesRead = source.Read(buf, 0, bufSize)) > 0) 
       target.Write(buf, 0, bytesRead); 
     } 
    } 
} 
+0

['HttpUtility.UrlEncode'](http://msdn.microsoft.com/en-us/library/system .web.httputility.urlencode.aspx)? – Oded

+0

@Oded使用UrlEncode可以避開異常,但會導致CreateRelationship引發「無效的URI:無法解析主機名」。 – HaemEternal

回答

2

System.IO.Packaging程序不允許 「#」 在名字