簡體   English   中英

拒絕訪問路徑“C:\\Users\\xxx\\Desktop”

[英]Access to the path 'C:\Users\xxx\Desktop' is denied

我已經徹底搜索了整個拒絕訪問的問題,但沒有發現任何與在我自己的系統上訪問 Windows 表單相關的問題,所有問題都與 Web 應用程序有關。

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
        byte[] imgdata;
        FileStream fsrw;
        string fname;
        openFileDialog1.Filter = "Sai Files(*.JPG;*.GIF)|*.jpg;*.gif|All files (*.*)|*.*";
        openFileDialog1.ShowDialog();//opens the dialog box
        fname = openFileDialog1.FileName;//stores the file name in fname
        pictureBox1.ImageLocation = fname;//gives the image location to picturebox
        fsrw = new FileStream("C:\\Users\\Sainath\\Desktop", FileMode.Open, FileAccess.ReadWrite);
        imgdata = new byte[fsrw.Length];
        fsrw.Read(imgdata, 0, Convert.ToInt32(fsrw.Length));
        fsrw.Close();
        string s = "insert into imagetest values(@p1,@p2)";
        SqlConnection con = new SqlConnection("server=.;Data Source=.;Initial Catalog=Work;Integrated Security=True");
        SqlCommand cmd = new SqlCommand(s, con);
        cmd.Parameters.AddWithValue("@p1", imgdata);
        cmd.Parameters.AddWithValue("@p2", fname);
        con.Open();
        int i = cmd.ExecuteNonQuery();
        con.Close();
        Console.WriteLine(i);
    }
}

由於 Windows 默認權限的工作方式,您可能必須以管理員身份運行程序/IDE 才能訪問該文件夾。

更多上下文:

該路徑通向一個文件夾 - 而不是一個文件。 我相信基於 C 的語言中的 FileStreams 實際上必須指向一個文件,而不是一個目錄:即。 C:\\Users\\Username\\Desktop\\file.extension

您可能沒有意識到您正在嘗試打開桌面文件夾,然后嘗試將其用作文件。

如果您的意圖是將圖像的字節寫入數據庫,那么您的代碼應該是

  fsrw = new FileStream(fname , FileMode.Open, FileAccess.ReadWrite);

"C:\\\\Users\\\\username\\\\Desktop"是我的目錄; 不是文件。

由於您正在嘗試打開文件,因此:

fsrw = new FileStream("C:\\Users\\Sainath\\Desktop", FileMode.Open, FileAccess.ReadWrite);

... 應該

var fullpath = Path.Combine("C:\\Users\\Sainath\\Desktop", fname);
fsrw = new FileStream(fullpath, FileMode.Open, FileAccess.ReadWrite);
  1. 確保使用完全限定的名稱,包括目標和源的文件名。 (例如 C:\\Source\\file.ext、C:\\Destination\\file.ext)

  2. Visual Studio 應以與您嘗試訪問的文件夾相同的訪問權限運行。 嘗試訪問諸如“我的文檔”之類的內容以及您不需要提升訪問權限的其他位置不應要求您提升 Visual Studio。

  3. 您不必“獲取”或更改通常可以從運行 VS 的同一用戶訪問的文件和文件夾的權限。

鏈接到源: 在此處輸入鏈接描述

我發現文件的只讀標志(當設置為打開時)會阻止 FileStream 和 MemoryMappedFile 對象打開和讀取文件。 有兩種解決方案: 取消只讀或者將FileStream/MemoryMappedFile改為在FileMode.Read/MemoryMappedFileAccess.Read中打開; FileStream 的默認讀/寫行為是讀/寫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM