I did like:

FileStream fs = new FileStream(System.IO.Path.GetTempPath() + @"\MyTempDir" + listBox1.SelectedItem", FileMode.Create);

And you know what happens? It partly works. It opens the files (if its a pdf file, it opens in a acrobat reader, if doc it opens in word,...) but there is no file in that directory. listBox1.SelectedItem hold the full name of the file (like: "myFile.doc").

Strange, why is not there? The code go through well, it creates the file, but the file it is not shown in the specified (MyTempDir) folder.

-----------------------------------------------------------------------------------------------------------------------------------------------------------

If I just simply declare the file name in the code like:

FileStream fs = new FileStream(System.IO.Path.GetTempPath() + @"\MyTempDir" + @"\myFile.doc", FileMode.Create);

It again creates the file but this time it even phisicly appears in the specified (MyTempDir) folder.

Why is there the difference between these two example?

Any ideas?

Try,

FileStream fs = new FileStream(System.IO.Path.GetTempPath() + @"\MyTempDir\" + listBox1.SelectedValue, FileMode.Create);

Try,

FileStream fs = new FileStream(System.IO.Path.GetTempPath() + @"\MyTempDir\" + listBox1.SelectedValue, FileMode.Create);

This is the same like I did in my 1st upper example.
Correct is:

FileStream fs = new FileStream(System.IO.Path.GetTempPath() + @"\MyTempDir\" + "\\" + listBox1.SelectedValue, FileMode.Create);

I would like to know something else.

I am doing the code, where are now stored temporary files, which need to be deleted when a user runs this application for the 2nd time (1st time there is no directory and no files in it).

For the 2nd time let`s presume there are files inside "MyTempDir".
So how to delete them at the 1st place?
I was trying to delete the whole folder but it throws an error, there are files inside this folder. So I defenatelly have to delete all files inside it.

How?
This code I have now:

if (System.IO.Directory.Exists(System.IO.Path.GetTempPath() + @"\MyTempDir"))
            {
                System.IO.Directory.Delete(System.IO.Path.GetTempPath() + @"\MyTempDir"); //I CAN NOT DELETE FOLDER IF THERE ARE FILES INSIDE OF IT
                System.IO.Directory.CreateDirectory(System.IO.Path.GetTempPath() + @"\MyTempDir");
            }
            else
                System.IO.Directory.CreateDirectory(System.IO.Path.GetTempPath() + @"\MyTempDir");

So how to delete files? And I do not know what kind of files I got inside.

Got it :)

if (System.IO.Directory.Exists(System.IO.Path.GetTempPath() + @"\MojaMapa"))
            {
                string[] datoteke = Directory.GetFiles(System.IO.Path.GetTempPath() + @"\MojaMapa");
                foreach (string datoteka in datoteke)
                {
                    File.Delete(datoteka);
                }                
            }
            else
                System.IO.Directory.CreateDirectory(System.IO.Path.GetTempPath() + @"\MojaMapa");

This is the same like I did in my 1st upper example.
Correct is:

FileStream fs = new FileStream(System.IO.Path.GetTempPath() + @"\MyTempDir\" + "\\" + listBox1.SelectedValue, FileMode.Create);

The code adatapost gave you wasn't the same as your original, or did you mean it gave the same result?

You need to be careful when accessing the selected item/value in a control. It is a common mistake, people expect the SelectedItem to return whatever the string in the control is but sometimes it will return something along the lines of "System.Windows.Controls.ComboBoxItem" :p

Also, rather than delete the files when you load the application, if they arent needed after the app closes, you could always delete them when the app closes :)

I know, and I am sorry for saying that. I noticed a bit too late (after 30 mins, which is the limit for editing posts). So I couldn`t change it.

I saw a bit later he added a sing "\" on the end of "TempDir".

Sorry ones again, really didnt see it.

But I do have another small problem.

I did the upper code which creates a temp folder in which will be saved files, retrieved from the database. But I want to delete these files and the best I could think of is to delete files in the next session (when user re-opens this app.). This code does this, but I have a problem, if there is one of these files still opened (the file uses another process).

How can I do the code for letting the user know, that if he want to run the application again , he has to close that file (if he opeded the file myFile.pdf, he has to close this file which is running in acrobat Reader )

if (System.IO.Directory.Exists(System.IO.Path.GetTempPath() + @"\MyTempDir"))
            {
                string[] files = Directory.GetFiles(System.IO.Path.GetTempPath() + @"\MyTempDir");
                foreach (string file in files)
                {
                    //HERE I AM MISSING AN ERROR MESSAGE!
                    File.Delete(file);
                }                
            }
            else
                System.IO.Directory.CreateDirectory(System.IO.Path.GetTempPath() + @"\MyTempDir");

And it is a good idea of deleteing them on app close () event.
But still I can not delete file, if this is opened, righ? So, please for some help. And consider that I do not know which file, maybe there are more files opened.

I got an error on ref : A parameter cannot have all the specified modifiers; there are too many modifers on the parameter.
This is my code:

private void MyForm_Load(object sender, EventArgs e)
        {
            if (System.IO.Directory.Exists(System.IO.Path.GetTempPath() + @"\MyFolder"))
            {
                string myFile;
                string[] allFiles = Directory.GetFiles(System.IO.Path.GetTempPath() + @"\MyFolder");
                foreach (string file in allFiles)
                {
                    IsFileOpen(out myFile);
                }
            }
            else
                System.IO.Directory.CreateDirectory(System.IO.Path.GetTempPath() + @"\MyFolder");
        }

        public bool IsFileOpen(out ref string file) //ref is here the problem, any clues why?
        {
                if ((File.GetAttributes(file) & FileAttributes.ReadOnly) != FileAttributes.ReadOnly)
                {
                    using (FileStream stream = new FileStream(file, FileMode.OpenOrCreate, FileAccess.Read, FileShare.None))
                    {
                        try
                        {
                            stream.ReadByte();
                            return false;
                        }
                        catch (IOException)
                        {
                            return true;
                        }
                        finally
                        {
                            stream.Close();
                            stream.Dispose();
                            File.Delete(file);
                        }
                    }
                }
                else
                    return true;
        }

No worries, it happens :p I was just checking to see if you meant you were getting the same problem.

Checking if the file is open is unfortunately not a simple thing to do. There is always the chance of a race condition (its not open when you check but gets opened before you delete it).

Your best bet is to use a try/catch. Ive included a while loop so it will continue to retry after the user has been notified. Be aware though, that this will mean the application will keep trying until the file is deleted. You could give the messagebox OK and Cancel buttons then capture the Cancel button to skip the file, but this is jsut a simple example for you :)

foreach (string file in files)
            {
                while (File.Exists(file))
                {
                    try
                    {
                        File.Delete(file);
                    }
                    catch (IOException ex)
                    {
                        MessageBox.Show("Error deleting file: " + file + Environment.NewLine
                        + "Please close all copies of the file before continuing");
                    }

                }
            }

Big thanks. IT works great.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.