how upload image to folder and display it - c#

I try to upload image to folder (using FileUpload) by pressing one submit button to whole form. i manage to upload the image to separate folders but i can't display it.
thank you.
String fname;
FileUpload tempFU = new FileUpload();
string path = Server.MapPath(".") + "\\images\\" + ulProj.groupCode;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
try
{
tempFU = (FileUpload)customerUC.FindControl("CustomerLogoUrlFU");
Directory.CreateDirectory(path);
fname = path + "\\" + tempFU.FileName;
tempFU.SaveAs(fname);
tempCus.logoUrl = fname;
}
catch
{
//return;
}

Points to remember:
you should use tilde ~ operator to represent the current project
root folder.
use System.IO.Path.Combine() to combine your path and filename to get the valid complete path.
you are creating the Directory for the given path 2 times. so remove the later part where you are creating the Directory 2'nd time.
as said in the above comments as your catch block is not having anycode,
remove the try-catch block
Complete Solution:
String fname;
FileUpload tempFU = new FileUpload();
string path = Server.MapPath(#"~\images\" + ulProj.groupCode);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
tempFU = (FileUpload)customerUC.FindControl("CustomerLogoUrlFU");
fname = System.IO.Path.Combine(path,tempFU.FileName);
tempFU.SaveAs(fname);
tempCus.logoUrl = fname;

Related

How to verify a file has been downloaded on my downloads directory on windowsd 10?

I have automated a test script in selenium and c# whereby I click on an icon and it downloads a pdf file. I do not know the name of this file, so what I need is confirmations its been downloaded, the file name and then it deletes the file?
I have done some research and found some code but it doesn't work. Here is the latest code I have found but all it tells me in "files" is the number of pdf files in my directory.
string fileName = ConfigurationManager.AppSettings["Don't know file name"];
string pathUser = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
string pathDownload = Path.Combine(pathUser, "Downloads");
DirectoryInfo downloadDir = new DirectoryInfo(pathDownload);
FileInfo[] files = downloadDir.GetFiles("*.pdf");
var file = files.Where(x => x.Name.Replace(" ", "") == fileName + ".pdf").FirstOrDefault();
fileName = file.FullName;
In case someone wants to know I have figured it out. So here is the code to confirm file has been downloaded and exists and then its deleted:
string pathUser = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
string pathDownload = Path.Combine(pathUser, "Downloads");
DirectoryInfo downloadDir = new DirectoryInfo(pathDownload);
FileInfo[] files = downloadDir.GetFiles("*.pdf");
var filename = files[0].FullName;
string getFileName = Path.GetFileName(filename);
if (File.Exists(filename))
{
Console.WriteLine("The file has been downloaded successfully");
Console.WriteLine("The filename is: " + getFileName);
}
File.Delete(filename);
Hope it helps someone.

Renaming the Copy of a Picture

I'm trying to create an album and what I want to do, is to copy a picture from its original path to a specific folder and rename (the copy) right after.
Here is a piece of my code (note that "picturedir" is a path):
string PCname = Environment.UserName;
Image File;
OpenFileDialog openfile = new OpenFileDialog();
openfile.InitialDirectory = #"C:\Users\" + PCname + #"\Pictures";
if (openfile.ShowDialog() == DialogResult.OK)
{
try
{
File = Image.FromFile(openfile.FileName);
pictureBox3.Image = File;
pictureBox3.Image.Save(picturedir + "\\" + openfile.SafeFileName);
System.IO.File.Move(picturedir + "\\" + openfile.SafeFileName,
picturedir + "\\" + "1");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
As seen in the last line inside the "try", I want to rename the chosen picture, simply to "1". However, this last line gives an error "Cannot create a file when that file already exists". Any ideas?
P.S.: If I do not use the last "try" line: System.IO.File.Move(picturedir + "\\" + openfile.SafeFileName, picturedir + "\\" + "1"); it does copy the chosen picture but it obviously does not rename it at all.
Here is an article about work with files.
From article:
static void Main()
{
string fileName = "test.txt";
string sourcePath = #"C:\Users\Public\TestFolder";
string targetPath = #"C:\Users\Public\TestFolder\SubDir";
// Use Path class to manipulate file and directory paths.
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
// To copy a folder's contents to a new location:
// Create a new target folder, if necessary.
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
// To copy a file to another location and
// overwrite the destination file if it already exists.
System.IO.File.Copy(sourceFile, destFile, true);
}
If you use different file names, you get copy with new name.

How to work with ImageButton in code behind in C#

protected void Button1_Click(object sender, EventArgs e)
{
try
{
if (FileUpload1.HasFile)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string path = Server.MapPath("~//Images//" + FileName);
FileUpload1.SaveAs(path);
string imagepathsource = path;
string imagepathdest = #"D:\\" + Session["brandname"].ToString() + "\\" + Seasonfolders.SelectedItem.Text + "\\" + stylefolders.SelectedItem.Text + "\\Images\\" + FileName;
File.Move(imagepathsource, imagepathdest);
uploadedimage.ImageUrl = "D://" + Session["brandname"].ToString() + "//" + Seasonfolders.SelectedItem.Text + "//" + stylefolders.SelectedItem.Text + "//Images//" + FileName;
}
}
uploadedimage is a ImageButton where I need to display the image using imageurl with that link. The image is not displaying and no error.. I could see when the above code gets execute the page is getting refreshed? What code can be added in this ??
ImageUrl needs an URL.
So instead of assigning it with a local file name on disk, use something like this (where ~ stands for 'application root folder':
uploadedimage.ImageUrl = "~/Images/yourImage.png"
You have to supply it with:
An image inside your application root folder;
An URL that is catched by a HttpHandler, that generates / loads the image from a different location (a little harder to do, but if you need to load from another location then inside application root, this is the best option).

Upload File attached to FileUpload Control to FTP C#

I am trying to upload a file that is attached to a FileUpload control to a folder that is created in FTP. The Folder is getting created without issue but I can't seem to upload the file.
It seems as though my filepath to the source file is incorrect in the line String filePath = Server.MapPath("~" + #"\" + nameToGiveFolder); I have tried multiple variations of the file path but cannot seem to get the file uploaded.
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = FileUpload1.FileName;
string ftphost = WebConfigurationManager.AppSettings["myHost"].ToString();
string u = WebConfigurationManager.AppSettings["u"].ToString();
string p = WebConfigurationManager.AppSettings["p"].ToString();
string nameToGiveFolder = FileUpload1.FileName.ToString().Substring(0, FileUpload1.FileName.ToString().LastIndexOf("."));
string ftpfullpath = "ftp://" + ftphost + "/" + nameToGiveFolder;
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
ftp.Method = WebRequestMethods.Ftp.MakeDirectory;
ftp.Credentials = new NetworkCredential(u, p);
FtpWebResponse CreateFolderResponse = (FtpWebResponse)ftp.GetResponse();
if (FileUpload1.HasFile)
{
try
{
Label1.Text = "Has File";
String filePath = Server.MapPath("~" + #"\" + nameToGiveFolder);
FileUpload1.SaveAs(filePath);
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
}
}
else
{
Label1.Text = "No File";
}
}
Use Path.GetFileNameWithoutExtension(). to get the file name
FileUpload1.SaveAs(Server.MapPath(string.Format("~/{0}/{1}", Path.GetFileNameWithoutExtension(FileUpload1.FileName), FileUpload1.FileName)));
Note that you need to give the file name as well, if the file name is abc.jpg, above code try to create folder under your root of the web side called abc and save the file inside that folder with file name abc.jpg
i think your problem of line String filePath = Server.MapPath("~" + #"\" + nameToGiveFolder); is only having folder path at the end. when you call FileUpload1.SaveAs you need to have full file path.
Update
You get the error
System.IO.DirectoryNotFoundException: Could not find a part of the
path
because you don't have directory with the name of file name. I'm not where exactly you want to put the file. if you going to put the file in new directory, you need to create that directory first.
var folderpath = Server.MapPath(string.Format("~/{0}", Path.GetFileNameWithoutExtension(FileUpload1.FileName)));
System.IO.Directory.CreateDirectory(folderpath);
FileUpload1.SaveAs(Path.Combine(folderpath, FileUpload1.FileName));

Saving Uploaded File with Unique Name in Folder

I need to save a file(image) to a folder.
If have an image with name "OrignalName", then its saving in their original name in to my specified folder. I'm using
string filename = Path.GetFileName(fileupload1.PostedFile.FileName);
GenerateFileName(filename);
fileupload1.SaveAs(Server.MapPath("Images" + filename));
How should i change the filename to a unique such as timestamp (yyyymmddMMss)
Any help will be appreciated.
System.IO.FileInfo file = new System.IO.FileInfo(FileUpload1.PostedFile.FileName);
string fname = file.Name.Remove((file.Name.Length - file.Extension.Length));
fname = fname + System.DateTime.Now.ToString("_ddMMyyhhmmss") + file.Extension;
Easily is save file to location and then rename him
string newName = System.DateTime.Now.ToString("ddMMyyhhmmss");
Microsoft.VisualBasic.FileIO.RenameFile(file, newName);
You can try with this code
var newPath = filename + DateTime.Now.ToString("yyyymmddMMss");
fileupload1.SaveAs(Server.MapPath("Images/" + newPath));
You can concate your file name with current date and time before saving it to database like that:
string strtemp = filename + System.DateTime.Now.ToString("ddMMyyhhmmss");
Try the following:
int generatedNo = randomNumber.Next(100, int.MaxValue);
string filePath=Path.Combine(Server.MapPath("~/finaldesign")+generatedNo+".jpg");
imageTosave.Save(filePath, ImageFormat.Jpeg);

Categories