Obaja Alfonsus Dhani
Obaja Alfonsus Dhani

Reputation: 175

Ensure directory exists or create if needed before saving a file

I have a file name that I am generating from data that is coming from a database. I need to save the file to a folder location that is coming from a database query. How do I ensure the path exists so that when I save my file it will not throw an exception about a missing directory? My file saving code is listed below. When I call saveTemp.Save I am getting an exception because the directory does not exist.

Image<Bgr, Byte> newImage = sourceImage.WarpPerspective(mywarpmat, 355, 288, Emgu.CV.CvEnum.INTER.CV_INTER_LINEAR, Emgu.CV.CvEnum.WARP.CV_WARP_FILL_OUTLIERS, new Bgr(0, 0, 0));
Image<Bgr, Byte> savetemp = newImage.Copy();

savetemp.ROI = new Rectangle(lokasiX, lokasiY, templatewidth, templateheight);
savetemp.Save(@"D:\Dokumen\Alfon\TA Alfon\CobaFitur\Template\Kotak\" + simpantmp["namakamera"].ToString() +  "Template_" + DateTime.Now.ToString("yyyyMMdd_hhmmss") + cnt + ".jpg");

Upvotes: 5

Views: 2886

Answers (1)

pstrjds
pstrjds

Reputation: 17448

You need to ensure the directory exists before you can save a file to it. You can do this using the Directory.CreateDirectory method. I would also modify your code to use the Path.Combine method to build your path.

var fileName = "Template_" + DateTime.Now.ToString("yyyyMMdd_hhmmss") + cnt + ".jpg");
var filePath = Path.Combine(@"D:\Dokumen\Alfon\TA Alfon\CobaFitur\Template\Kotak", simpantmp["namakamera"].ToString());
Directory.CreateDirectory(filePath);
saveTemp.Save(Path.Combine(filePath, fileName)); 

Upvotes: 6

Related Questions