c# - System.UnauthorizedAccessException 访问路径被拒绝

标签 c# exception .net pdf-writer

尝试使用以下代码编写 PDF 文档:

document = new Document();
PdfWriter writer = null; ;
try
{
    writer = PdfWriter.GetInstance(document, new FileStream(@"E:\mergFiles", FileMode.Create));
}
catch (Exception xc)
{ }

我遇到异常:

{System.UnauthorizedAccessException: Access to the path 'E:\mergFiles' is denied.
   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, Boolean useLongPath)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
   at System.IO.FileStream..ctor(String path, FileMode mode)
   at PDFLibrary.PDFManager.MergeDocs()}

我可以访问这个文件夹。

目视并发现这可以帮助 File.SetAttributes(@"E:\mergFiles", FileAttributes.Normal); 但我仍然遇到相同的异常。

最佳答案

嗯,您不能将文件夹的名称传递给 FileStream。它需要是一个包含路径的文件名(编辑:当然,如果您使用相对文件名,它实际上并不必须包含路径)。

如果要创建文件夹,请使用 Directory.CreateDirectory。要在该文件夹中创建文件,请使用如下内容:

string fullName = Path.Combine(pathName, fileName);
writer = PdfWriter.GetInstance(document, new FileStream(fullName, FileMode.Create));

关于c# - System.UnauthorizedAccessException 访问路径被拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18374200/

相关文章:

C#:为什么 0xFFFFFFFF 在表示 -1 时是一个 uint?

java - CompletableFuture#异常地重新抛出已检查的异常

c++ - 如何在没有OOM killer 的情况下发出C++终止捕获

.net - 异常处理最佳实践

.net - 在 ASP.NET 中使用更少的内存

c# - 从 .NET 正则表达式对象获取命名组子模式

c# - 如何检测 C# 回调处理程序发送者

c# - Visual Studio MySQL 数据集错误

c# - 如何为 .Where(x => x.<deep property>.Select(y => y.id).Intersect(List<int>).Any()) 创建表达式树

c# - 如何从Azure存储表中选择缺少字段的记录?