gpt4 book ai didi

c# - 当路径包含 # 时创建部分 URI

转载 作者:太空宇宙 更新时间:2023-11-03 11:09:46 28 4
gpt4 key购买 nike

我正在使用下面的代码压缩一个文件。我发现当压缩路径中的文件夹包含哈希 (#) 时,CreatePartUri(uri) 会引发异常:

Part URI cannot contain a Fragment component.

由于我无法更改文件夹名称,如何转义路径中的 # 符号以便正确创建 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 不允许在名称中使用“#”

关于c# - 当路径包含 # 时创建部分 URI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14499481/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com