1

I am new at programming and I'm trying to upload an image and save it in folder with the current product id. However when I update the image a new folder is created. Instead of return maxId++, how can I store the ID in DataContext and return that if it exists? Here goes the code.

    private void upload_Click_1(object sender, EventArgs e)
    {
        OpenFileDialog opFile = new OpenFileDialog();
        opFile.Title = "Select image for this product";
        opFile.Filter = "jpg files (*.jpg)|*.jpg|All files (*.*)|*.*";
        if (opFile.ShowDialog() == DialogResult.OK)
        {
        try
        {
            string iName = opFile.FileName;
            var dir = @"images/" + GetCurrentId();
            var path = Path.Combine(dir, Path.GetFileName(iName));

            if (!Directory.Exists(dir) &&(produto)this.tbprodutoBindingSource.Current == null))
            {
                Directory.CreateDirectory(dir);
            }

            File.Copy(iName, path);
        }
           catch (Exception ex)
        {
            MessageBox.Show("Unable to open file " + ex.Message);
        }
    }
    else
    {
        opFile.Dispose();
    }
        }

    private int GetCurrentId()
    {
        var result = dataContextFactory.DataContext.produtos.Max(x => x.id_produto);
        int maxId = Convert.ToInt32(result);
        if (maxId == 0) maxId = 1;
        else
            maxId++;

        return maxId;

    }
leandro
  • 13
  • 3
  • Here's a career tip: using MAX to get the next id is *always* wrong, for several reasons. An ID should be auto-incrementing. Insert your record then get the id that was generated by the database. – Crowcoder May 07 '19 at 11:30

3 Answers3

0

I don't really get what you want, but I'll try to solve the problem that I get.

  1. Did you want to create a new folder everytime a new photo is uploaded, or you want to rename the photo into [Id][FileName].jpg? If you want the latter, you can change this
var dir = @"images/" + GetCurrentId();
var path = Path.Combine(dir, Path.GetFileName(iName));

into this

var dir = @"images";
var fileName = GetCurrentId() + Path.GetFileName(iName);
var path = Path.Combine(dir, fileName);
  1. If you want an auto increment id, you should put the auto increment on database, not by fetching last id and increment it. However, if your id is not really important (you just need it as unique identifier), you can consider using uuid instead of auto increment. For some example, you can refer to here.
string id = Guid.NewGuid().ToString();
  1. File.Copy(iName, path) doesn't require the same file name iName and path, you can change the name and that won't generate any problem.

  2. If the product is a new record, you can generate uuid, use it for the image, then use it for the product id.

string id = Guid.NewGuid().ToString();
Product newProduct = new Product();
newProduct.ProductID = id;
var dir = "@images";
var path = Path.Combine(dir, id);
File.Copy(iName, path);

If the product is old record, you can get the id from the product, and use that id for the image name.

Product existingProduct = getProduct();
string id = existingProduct.GetID();
var dir = "@images";
var path = Path.Combine(dir, id);
File.Copy(iName, path);
  • What you propose will not work, I am trying to add the products details along the image on database, but I want to store the image along the product id which auto number but since it has not been created, I cant get the id from it. That why I'm doing max+1, however when I update it creates a new folder. I want to get the id from the product that hasn't been created yet – leandro May 07 '19 at 13:00
  • How can I get the productBindingSource.Current ID? – leandro May 07 '19 at 13:01
  • Could anybody help me? – leandro May 07 '19 at 14:38
  • You can generate a [uuid using C# library](https://learn.microsoft.com/en-us/dotnet/api/system.guid.newguid?redirectedfrom=MSDN&view=netframework-4.8#System_Guid_NewGuid) to get the uuid before inserting. – sulfurizedDuck May 08 '19 at 01:38
  • Any example where can I find? – leandro May 08 '19 at 09:05
  • Simply using `string id = Guid.NewGuid().ToString();` works for me, but you can refer to [here](https://stackoverflow.com/questions/8477664/how-can-i-generate-uuid-in-c-sharp) if it is not enough. – sulfurizedDuck May 08 '19 at 10:17
  • I mean I am using File.Copy(iName, path), for that reason I can't change the name of image that was uploaded, after that I am adding a new item to the gridview datasource. I want to get the id from the current record – leandro May 09 '19 at 16:11
  • Or least manage to create one record and add the same id to the folder and when I update something on the record instead of creating a new folder, to update that same folder, but for that I need to check if the current id is null or not – leandro May 09 '19 at 16:12
  • Edited the answer, maybe you can find the solution there. – sulfurizedDuck May 11 '19 at 05:35
0

File.Copy(iName, path) doesn't require the same file name iName and path, you can change the name and that won't generate any problem. Actually it causes an error because I am coping the file, when I change the name of the image it causes an error and the image cannnot be uploaded.

I don't want to create a folder everytime I upload an image, I want ajust the product Id, that has not been created yet, to image folder. If the current product Id is 22, I need a folder with the name 22 and its images on it. What has been purposed allows me to update as well?

leandro
  • 13
  • 3
0

File.Copy(iName, path) doesn't require the same file name iName and path, you can change the name and that won't generate any problem. Actually it causes an error because I am coping the file, when I change the name of the image it causes an error and the image cannnot be uploaded.

I tried copying an image to another path and it doesn't cause any problem. But if the image's name is determined by your upload, it can't be helped then.

I don't want to create a folder everytime I upload an image, I want ajust the product Id, that has not been created yet, to image folder. If the current product Id is 22, I need a folder with the name 22 and its images on it.

You can achieve this using something like this:

var dir = @"images/" + imageID;
var path = Path.Combine(dir, Path.GetFileName(iName));
File.Copy(iName, path);

What has been purposed allows me to update as well?

Yes. You might want to delete the old image before uploading the new image.

// Delete the old image in the folder
var dir = @"images/" + imageID;
string oldImageName = Directory.GetFiles(dir).FirstOrDefault();
File.Delete(oldImageName);

// Copy the new image to the folder
var path = Path.Combine(dir, Path.GetFileName(iName));
File.Copy(iName, path);