当路径包含 # 时创建部件 URI
本文关键字:创建部 URI 路径 包含 | 更新日期: 2023-09-27 17:55:32
我正在使用下面的代码压缩文件。我发现当被压缩的路径中的文件夹包含哈希 (#) 时,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);
}
}
}
System.IO.Packaging 不允许在名称中使用"#"
正如 Rockstart 所说,Uri 中不允许使用"#"在创建 Uri 以删除 # 字符之前,请使用此选项:
fileName = Regex.Replace(fileName, "#", "");