You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows Forms图书管理系统添加图片遇System.UnauthorizedAccessException错误

Windows Forms图书管理系统添加带图片书籍时的权限错误问题

错误信息

System.UnauthorizedAccessException: Access to the path C:\User\WINDOWS 10\source\repos\LibraryManagementSystem\LibraryManagementSystem\BooksDirectory is denied.
at System.IO_Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.Directory.InternalCreateDirectory(String fullPath, String path, Object dirSecurityObj, Boolean checkingHost)
at System.IO.Directory.InternalCreateDirectoryHelper(String path, Boolean checkingHost)
at System.IO.Directory.CreateDirectory(String path)
at LibraryManagementSystem.AddBooks.addBtn_Click(Object sender, EventArgs e) in C:\User\Acer\source\repos\LibraryManagementSystem\LibraryManagementSystem\AddBooks.cs:line88

相关代码

private void addBtn_Click(object sender, EventArgs e)
{
    if (picture.Image == null
        || booktitleTxt.Text == ""
        || authorTxt.Text == ""
        || published.Value == null
        || status.Text == ""
        || picture.Image == null)
    {
        MessageBox.Show("Please fill all blank fields", "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    else
    {
        if (connect.State == ConnectionState.Closed)
        {
            try
            {
                DateTime today = DateTime.Today;
                connect.Open();
                string insertData = "INSERT INTO books " +
                    "(book_title, author, published_date, status, image, date_insert) " +
                    "VALUES(@bookTitle, @author, @published_date, @status, @image, @dateInsert)";

                string path = Path.Combine(@"C:\Users\WINDOWS 10\source\repos\LibraryManagementSystem\LibraryManagementSystem\BooksDirectory\" +
                    booktitleTxt.Text + authorTxt.Text.Trim() + ".jpg");

                string directoryPath = Path.GetDirectoryName(path);

                if (!Directory.Exists(directoryPath))
                {//Bellow is line 88
                 Directory.CreateDirectory(directoryPath);
                }

                File.Copy(picture.ImageLocation, path, true);

                using (SqlCommand cmd = new SqlCommand(insertData, connect))
                {
                    cmd.Parameters.AddWithValue("@bookTitle", booktitleTxt.Text.Trim());
                    cmd.Parameters.AddWithValue("@author", authorTxt.Text.Trim());
                    cmd.Parameters.AddWithValue("@published_date", published.Value);
                    cmd.Parameters.AddWithValue("@status", status.Text.Trim());
                    cmd.Parameters.AddWithValue("@image", path);
                    cmd.Parameters.AddWithValue("@dateInsert", today);

                    cmd.ExecuteNonQuery();

                    displayBooks();

                    MessageBox.Show("Added successfully!", "Information Message", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    clearFields();
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
            finally
            {
                connect.Close();
            }
        }
    }
}

已尝试操作

已为BooksDirectory文件夹及其主文件夹赋予完全权限,但问题仍未解决。

解决方案建议

  • 修复路径拼写错误:错误日志中显示的路径是C:\User\...(单数User),但代码中写的是C:\Users\...(复数Users),路径不匹配可能导致系统找不到目标目录,进而触发权限报错,先确认目标文件夹的实际路径是否正确。
  • 改用应用程序专用目录存储图片:系统盘的用户开发目录通常有严格的权限控制,建议使用Windows提供的应用程序数据目录来存储图片,避免权限问题。修改路径代码如下:
    // 获取应用程序数据目录
    string appDataDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
    // 创建专属的书籍图片目录
    string booksDir = Path.Combine(appDataDir, "LibraryManagementSystem", "BooksDirectory");
    // 过滤文件名中的非法字符
    string safeFileName = $"{booktitleTxt.Text.Trim()}{authorTxt.Text.Trim()}"
        .Replace("\\", "").Replace("/", "").Replace(":", "")
        .Replace("*", "").Replace("?", "").Replace("\"", "")
        .Replace("<", "").Replace(">", "").Replace("|", "");
    string path = Path.Combine(booksDir, $"{safeFileName}.jpg");
    
  • 以管理员身份运行程序/Visual Studio:即使设置了文件夹权限,程序运行时可能没有足够的权限访问目录,右键点击Visual Studio或生成的程序,选择以管理员身份运行再测试。
  • 过滤文件名中的非法字符:直接拼接书名和作者名可能包含Windows文件名禁止的字符(如\ / : * ? " < > |),这会导致文件创建失败,需要先过滤这些字符,避免后续报错。
  • 验证图片源路径有效性:确认picture.ImageLocation是否为有效的本地文件路径,如果是通过OpenFileDialog选择的图片,确保用户没有取消选择或者路径不存在。

内容的提问来源于stack exchange,提问作者Ryuu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 05:13:10