0

I met one problem when I tried to copy file. Error description enter image description here

I worked with DataGridView and PictureBox. Deguber of VS 2015 stopped me at

FileStream fs = File.Open(file, FileMode.Open);

in function CopyFile. I cant understand what's wrong i did.

This is some code (C#, .NET 4.5.1) from main form:

    static string CopyFile(string file, string to)
    {
        FileInfo fileInfo = new FileInfo(file);
        byte tmp = 0;
        string temp = to + "\\" + fileInfo.Name;
        FileStream newFile = File.Open(temp, FileMode.Create);
        try
        {
            FileStream fs = File.Open(file, FileMode.Open);
            for (int i = 0; i < fileInfo.Length; i++)
            {
                tmp = (byte)fs.ReadByte();
                newFile.WriteByte(tmp);
            }
            fs.Close();
        }
        catch (FileNotFoundException ex)
        {
            MessageBox.Show("Не вдалося найти файл.");
        }
        newFile.Close();
        return temp;
    }
    private void WriteNewUserToFile(User item, string pathToFile)
    {
        StreamWriter sw = new StreamWriter(File.Open(@pathToFile, FileMode.Append, FileAccess.Write));
        sw.WriteLine(string.Format("{0}, {1}, {2}, {3}, {4}, {5}",
            item.Id,
            item.Image,
            item.FirstName,
            item.LastName,
            item.Email,
            item.Phone));
        sw.Close();
    }

    private void btnAddUser_Click(object sender, EventArgs e)
    {
        AddUserForm dlg = new AddUserForm();
        if (dlg.ShowDialog() == DialogResult.OK)
        {
            User item = dlg.NewUser;
            item.Image = CopyFile(item.Image, "images");
            WriteNewUserToFile(item, "data/users.dat");
            users.Add(item);
            //this.AddNewDataGridRow(item);
        }
    }

And some code of AddNewUserForm:

    public User NewUser
    {
        get { return newUser; }
        set { newUser = value; }
    }

    private void btnImage_Click(object sender, EventArgs e)
    {
        OpenFileDialog dlg = new OpenFileDialog();
        if (dlg.ShowDialog() == DialogResult.OK)
        {
            txtImage.Text = dlg.FileName;
            try
            {
                picboxImage.Image = Image.FromFile(txtImage.Text);
            }
            catch
            {
                picboxImage.Image = Image.FromFile(@"images\NoImg.bmp");
            }
        }
    }

    private void btnApply_Click(object sender, EventArgs e)
    {
        NewUser = new User
        {
            Id = Convert.ToInt32(txtId.Text),
            LastName = txtLastName.Text,
            FirstName = txtFirstName.Text,
            Email = txtEmail.Text,
            Phone = txtPhone.Text,
            Image = txtImage.Text
        };
        this.DialogResult = DialogResult.OK;
    }

If somebody need all project/code, click here (download VS project).

Jeidoz
  • 54
  • 9
  • Well, the reason is pretty clearly stated in the error text - something else is holding that file, and this is why your code can't read it. All you need to do is to find what is holding it. It can be some external program or your own code in the very same project... there's a field for research here, but we can only guess. Or try to restart your computer, maybe some program had crashed before and did not release its holds. – Alexander Leonov Apr 29 '17 at 19:42
  • @AlexanderLeonov Problem in my code/project, i didnt use this file in other programs. I tried CopyFile in empty WinForms project and all was okey, but in this project I got unknown process which block my file (image), i think its can be DataGridView (column of pics) or PictureBox.Image. This is all my options but in spite of this variants, i dont know how to get rid of this problem. – Jeidoz Apr 29 '17 at 19:50

1 Answers1

1

When you set the Image for the PictureBox using the following code, the call keeps the file handle open. So when you try to open the file again you encounter the exception.

picboxImage.Image = Image.FromFile(txtImage.Text);

According to this accepted answer, when the file handle is closed is unpredictable, in some cases, the handle won't be closed even if you explicitly close the Image.

So you may use the technique in that answer like this, to ensure the file handle is closed properly.

picboxImage.Image = Image.FromStream(new MemoryStream(File.ReadAllBytes(txtImage.Text))); 
Community
  • 1
  • 1
kennyzx
  • 12,845
  • 6
  • 39
  • 83