访问路径"C:\ Users\xxx\Desktop"被拒绝

Sai*_*ath 27 c# permissions access-denied winforms

我已经彻底搜索了整个访问被拒绝的问题,并且没有找到任何与我自己的系统上访问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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Ric*_*ner 37

您可能必须以管理员身份运行程序/ IDE才能访问该文件夹.我不确定为什么,但我遇到了同样的问题.与默认Windows权限有关.如果有效,请告诉我们!

编辑:

路径指向文件夹 - 而不是文件.我相信基于C语言的FileStreams实际上必须指向一个文件,而不是一个目录:ie.C:\Users\Username\Desktop\file.extension.您可以尝试一下,让我们知道它是否有帮助?


Ste*_*eve 6

可能您没有意识到您正在尝试打开Desktop文件夹,然后尝试将其用作文件.

如果您的目的是将图像的字节写入数据库,那么您的代码应该是

  fsrw = new FileStream(fname , FileMode.Open, FileAccess.ReadWrite);
Run Code Online (Sandbox Code Playgroud)


Aus*_*nen 5

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

由于您正在尝试打开该文件,因此:

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

... 应该

var fullpath = Path.Combine("C:\\Users\\Sainath\\Desktop", fname);
fsrw = new FileStream(fullpath, FileMode.Open, FileAccess.ReadWrite);
Run Code Online (Sandbox Code Playgroud)