0

For my project I'm setting up a page where you can change your profile and upload an image. I've got all of that to work but now I want to make my image unique by matching the file name with the Username (which already is unique) but I couldn't find a good guide anywhere on google. Here is my code:

{ 
    if (PfFoto != null)
    {
        string pic = System.IO.Path.GetFileName(PfFoto.FileName);

        string path = System.IO.Path.Combine(Server.MapPath("/images/PFfotos"), pic);

        PfFoto.SaveAs(path);

        return RedirectToAction("Index");
    }                               
}

My username is stored in changePF.Name and the file name is stored in pic

so does anyone know how to do this?

5
  • Why do you want to combine the file name with the username? Why not just assign it a unique random ID? Commented Dec 2, 2017 at 0:23
  • Becouse I need to display this image as a pf pic and its easy if the file name is the same as the user name used to login Commented Dec 2, 2017 at 1:07
  • You think it's easy. But it's actually a bad idea.What if the username were to change? You should base this off the user's ID, which should be a totally made up value not based on any attribute of the user that might change. Commented Dec 2, 2017 at 2:17
  • Okay yea I might overlooked that ill test and see what happens and then Change it to use the ID if necessary I allready got a static id from the db I use Commented Dec 2, 2017 at 8:36
  • If you need multiple photos per user, then each file should have a separate ID that's stored in a database table that has a foreign key back to the UserId. Commented Dec 2, 2017 at 12:27

2 Answers 2

1

Simply change FileName before SaveAs like :

if (PfFoto != null)
{
    string path = System.IO.Path.Combine(Server.MapPath("/images/PFfotos"), changePF.Name);

    PfFoto.SaveAs(path);

    return RedirectToAction("Index");
}  
Sign up to request clarification or add additional context in comments.

Comments

0

If you want your file name to be same as your user name (without the extension part matching), You may use the Path.GetExtension method to get the file extension(ex : .jpg or .png) and concatenate that with your unique username.

if (PfFoto != null)
{
    var newFileName = changePF.Name + Path.GetExtension(PfFoto.FileName);
    var path = System.IO.Path.Combine(Server.MapPath("/images/PFfotos"), newFileName);
    PfFoto.SaveAs(path);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.