Access to the path 'path' is denied. VS2017

Asked

Viewed 591 times

1

I am trying to create a file and save it in a folder created by me with the name "temporario". I created this folder on disk E: and inside my program, on disk C:. Using File.Create(file), error appears

Acess to the path 'E:\temporario' is denied.

Or, in the case of the folder in my program

Access to the path 'C:\Users\srodrigues\Documents\ProjetoPAP\ConversorPDFImage\Main\temporario' is denied.

I’ve researched a number of sites, in English and Portuguese, and it talks all about giving uncheck on the "Read only" option of the folder and I’ve done it, giving my user permission to write in the folder and I still have the same error.

What can I do to save the file in that folder? I prefer to keep it in the program folder.

OBS: I am manipulating PDF files and if I use document.Save(filepath) of Pdfsharp, saves in both folders without any problem, never had trouble saving files in folder E:\temporario, but now even that folder is not enough to save the file.

EDIT: I will put my code here - now complete (with the amendment proposed by Augusto Vasques):

    int indexi = 0;
    private void proc2_Click(object sender, EventArgs e)
    {
        openFileDialog1.Title = "Procurar arquivos no computador";
        openFileDialog1.InitialDirectory = @"E:\";
        openFileDialog1.Filter = "Imagens (.bmp,.jpg,.png,.tiff,.tif) |*.bmp;*.jpg;*.png;*tiff;*tif|Todos os arquivos (*.*)|*.*";
        DialogResult resposta = openFileDialog1.ShowDialog();

        if (resposta == DialogResult.OK)
        {
            foreach (string file in openFileDialog1.FileNames)
            {
                string caminhoCompleto = file;
                caminho2 = openFileDialog1.SafeFileName;
                caminhotb2.Text = caminhoCompleto;
                string fish = "";
                string path = @"E:\\temporario";

                using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    if (Directory.Exists(path))
                    {
                        fish = Path.Combine(path, caminho2);
                    }
                    else
                    {
                        Directory.CreateDirectory(path);
                        fish = Path.Combine(path, caminho2);
                    }
                    File.Create(fish);
                }          
                indexi = listaimg.Items.Count;
                listaimg.Items.Add((indexi + 1) + "- " + caminho2);
            }
        }
    }         
  • 1

    This is probably because you are trying to create a directory using a resource used to create files. Try using a adequate recourse and see if things work out as expected. Or, if I got it wrong: because you are trying to create a file, but you are not mentioning what this file is, as you yourself highlighted in the address above. The address is written only until the file "temporario" and is interrupted there. This is an error. It is necessary to specify the file

  • Thanks for the comment Caio, but I do not want to create a directory but a file inside the folder. The problem is, when I try to do it, it makes a mistake.

  • Try to save this file with an administrator user. Or sometimes it may even be a Windows related problem. Delete the folder and create another one with the same name.

  • @Caio de Paula Silva I put my code, take a look

  • @Pedroduca I deleted the folder and created it again, but I still have the same mistake. I am a network user but they put some administrator permissions for me to use, and I am running Visual Studio as Administrator.

  • Sofia, you guarantee that in addition to the path you are also specifying the file name to be created?

  • This temporary file is a PDF, right?

  • @Pedroduca No, the temporary file is an image (it can be PNG, JPG, BMP or TIFF) and then convert to PDF. When I gave the PDF example, it is because I also want to convert PDF to image, so I save PDF files in a temporary folder.

  • E:\ is a unit on your machine or a network mapping?

  • E: is the unit of the machine

Show 5 more comments

3 answers

2

There are three of your problems:

First problem:

You are trying to create a file when the permission you granted to your FileStream is sufficient only for reading. Change the FileMode and the FileAccess deforms to suit your needs.

Second Problem:

When trying to solve the first problem you created a variable path of tests that set the path to the FlieStream in a directory that does not exist and forgot to return to the original variable that is caminhotb2.Text.

Third problem:

You don’t need the line File.Create(fish); for the FileStream has already created your archive.

Try this:

using (FileStream fs = new FileStream(caminhotb2.Text, FileMode.OpenOrCreate,FileAccess.ReadWrite, FileShare.ReadWrite))

and comment or delete the line File.Create(fish);

  • I appreciate the answer, but it still makes a mistake... In fact this could be one of my code mistakes, but I think it’s something different.

  • @Sofiarodrigues I made a modification in the answer where I fixed and tested the solution. I kept the same objects of your code, but I advise using a SaveFileDialog instead of a OpenFileDialog

  • 1

    The problem of using the SaveFileDialog is that, so, instead of opening files to then, in the background, be saved in the folder, I will save files that do not even exist in the context of the program... But otherwise, the mistake is gone!

  • Thank you Augusto Vasques. It works, but I still can’t keep the file in the folder... I changed the FileMode.OpenOrCreate for FileMode.Create only, and still not holding

  • Use the method Write of FileStream

  • 1

    Already solved, published the reply. Thank you

Show 1 more comment

1

Try specifying the file extension

For example:

string caminho2 ="E:\\temporario.png";
  • I probably expressed myself badly, but I will try to explain what I intend. The directory of the folder where I want to save the file is "E: temporario", the name of the file and the extension are not always the same, so I can’t define the path with that name and this extension because both may vary.

  • Hence, as the extension varies, you can make it recognize the extension with Path.Getextension(E:);

  • Then you’d have to do something like;string caminho2 = openFileDialog1.SafeFileName;
string ex = Path.GetExtension(caminho2);
string path = @"E:\\temporario";
fish = Path.Combine(path, caminho2, ex); 
File.Create(fish); ??

  • Right!

  • If I do it that way, give me the mistake 'Could not find a part of the path 'E:\temporario\sol.jpg\.jpg'.' because when adding the extension to a file whose name already contains the extension, it gives this error because it adds the extension as if it were a directory.

  • 1

    I already solved the problem, published the answer. Thank you

  • 1

    Now I understood, when you joined the strings the "way2" already had the extension

Show 2 more comments

1


I managed to correct this mistake by adding the tips of Pedro Duca and Augusto Vasques, thank you both!

EDIT: I had to change the code because I was removing the contents of the initial file, now just copy.

So the final answer will be:

            foreach (string file in openFileDialog1.FileNames)
            {
                // Obtém o caminho completo do arquivo
                string caminhoCompleto = file;
                caminho2 = openFileDialog1.SafeFileName;
                caminhotb2.Text = caminhoCompleto;
                string StartDirectory = caminhoCompleto;
                string EndDirectory = @"C:\temporario";

                using (FileStream SourceStream = File.Open(file, FileMode.Open))
                {
                    using (FileStream DestinationStream = File.Create(EndDirectory + file.Substring(file.LastIndexOf('\\'))))
                    {
                        SourceStream.CopyToAsync(DestinationStream);
                    }
                }
                indexi = listabmp.Items.Count;
                listabmp.Items.Add((indexi + 1) + "- " + caminho2);
            }

The code was taken from here LINK.

  • Mark your answer as the answer to the question.

  • I can only accept as a solution two days after publishing the reply. So tomorrow I will mark

  • I found that the above code deletes the contents inside the file... I do not advise using!

  • It overwrites the file that has the same name, right ?

  • Right, but without any content. Is he subscribing to the right file? Instead of creating a new one in another location

  • 1

    In case there is no content at first he will create the file with File.Create(). The ideal would be to have a treatment for if you don’t have the file he created, as he had already done in the question code

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.