Changing Image Upload Name - c#

I want to create a name for the Image uploaded that will be stored as a variable Instead of
("ProfilePictures\\" + ProfilePicUpload.FileName));
I want to have something like
("ProfilePictures\\" + fileName));
So that i can name the images however I like without hard coding it.
Whenever I try to do it it creates some GuoSavEE type file.
protected void Upload_Click(object sender, EventArgs e)
{
try
{
string fileName = "abc";
ProfilePicUpload.SaveAs(Server.MapPath("ProfilePictures\\" + fileName));
}
catch(Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}

Related

save the content of the text box to a variable c#

I have the following method in windows form
private void btnSelectNuevo_Click(object sender, EventArgs e)
{
if (openFileDialog2.ShowDialog() == DialogResult.OK)
{
try
{
string fichero = openFileDialog2.FileName.ToString();
txtbox_sel_fich.Text = fichero;
if (string.IsNullOrEmpty(txtbox_sel_fich.Text) == true)
{
MessageBox.Show("file not selected", "return file selection", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
catch (SecurityException ex)
{
MessageBox.Show($"Security error.\n\nError message: {ex.Message}\n\n" +
$"Details:\n\n{ex.StackTrace}");
}
}
}
and another method:
private void btnsubir_Click(object sender, EventArgs e)
{
string reply = "";
string fichero = "";
fichero = textbox_select.Text.ToString();
// string ruta = textbox_select.Text.ToString();
// FileInfo fich = new FileInfo(ruta);
// fichero = fich.Name;
if (fichero == readLastFile(fichero))
{
createLog(fichero + ":this file" + fichero + " You have already been imported previously. No action is realized\n");
MessageBox.Show("This file" + "'" + fichero + "'" + " You have already been imported");
}
else
{..
how can you see I have a method called "readLastFile (fichero)"; what it does is check in MySql in the "File" table if there is a file already imported with that name that I pass as a parameter, if it exists it does not import it to the DDBB and the program ends but if it does not exist it does the import.
The problem I have is that the file variable stores the entire path of an excel file (c: \ ... \ helloWord.xlsx) when what I want is that it only stores (helloWord.xlsx) since when I am going to do the check tells me it doesn't exist and starts loading when it shouldn't.
Some help?
I don't know if I am saving it correctly. THANKS FOR YOUR SUPPORT
I have is that the file variable stores the entire path of an excel file (c: \ ... \ helloWord.xlsx) when what I want is that it only stores (helloWord.xlsx)
Use Path.GetFileName(...)
Path is part of the System.IO namespace

Change name and move file in C#

private void btn_add_image_Click(object sender, EventArgs e)
{
openFileDialog1.Title = "Choose a file";
openFileDialog1.InitialDirectory = "C:\\";
openFileDialog1.Filter = " JPEG Files (*.jpg;*.jpeg;*.jpe;*.jfif)|*.jpg|All Files (*.*)|*.*";
openFileDialog1.ShowDialog();
string file_name = openFileDialog1.FileName;
string filename2 = openFileDialog1.SafeFileName;
pictureBox1.Image = Image.FromFile(file_name);
}
private void button1_Click(object sender, EventArgs e)
{
try
{
pictureBox1.Image.Dispose();
pictureBox1.Image = null;
string[] extension = getExtension("images\\" + userid);
if (File.Exists("images\\" + userid + extension[0]))
{
File.Delete("resimler\\" + userid + extension[0]);
}
}
catch (Exception)
{
MessageBox.Show("İmage cannot find");
}
I want to Change File name and save , so i wrote this code if file exists , than delete file and save the choosen with userid name but i cant do change name and save file
if (File.Exists(#"\path\to\source"))
{
File.Move(#"\path\to\source",#"\path\to\destination")
}
I think both your problems can me handled with this bit of code.
System.IO.File.Move("old_file_name_path", "new_file_name_path");
This moves the file to a new filename. Take a look here: File.Move
But, I really don't get what you are asking here:
i wrote this code if file exists , than delete file and save the
choosen with userid name but i cant do change name and save file
Can you be more specific?
Thanks All
private void btn_save_Click(object sender, EventArgs e)
{
pictureBox1.Image.Dispose();
pictureBox1.Image = null;
string source = openFileDialog1.FileName;
string[] extension = getExtension(source);
string destination = "images\\" + userid + extension[0];
System.IO.File.Move(source, destination);
pictureBox1.Image = Image.FromFile("images\\" + userid + extension[0]);
}

Passing Value from function to class level variable always null

I defined a string variable at class level and set this variable in protected void UploadButton_Click(object sender, EventArgs e) after uploading the file successfully.
I do this so that i can pass value of fileName variable from this function to another
protected void btnSave_Click(object sender, EventArgs e) {} where i save it in the database. but value always is null. Am i doing something wrong or it remain null as functions are defined as Protected type
public partial class News: System.Web.UI.Page
{
string _fileName = null;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// some code here......
}
}
protected void UploadButton_Click(object sender, EventArgs e)
{
if (FileUploadControl.HasFile)
{
try
{
System.IO.FileInfo f = new System.IO.FileInfo(FileUploadControl.PostedFile.FileName);
if (f.Extension.ToLower() == ".pdf" || f.Extension.ToLower() == ".doc" || f.Extension.ToLower() == ".docx")
{
//3MB file size
if (FileUploadControl.PostedFile.ContentLength < 307200)
{
string filename = Path.GetFileName(FileUploadControl.FileName);
if (!System.IO.File.Exists("../pdf/news/" + FileUploadControl.FileName))
{
FileUploadControl.SaveAs(Server.MapPath("../pdf/research/") + filename);
StatusLabel.Text = "Upload status: File uploaded!";
_fileName = FileUploadControl.FileName;
}
else
{
_fileName = null;
StatusLabel.Text = "File with this name already exsists, Please rename file and Upload gain";
}
}
else
{
_fileName = null;
StatusLabel.Text = "Upload status: The file has to be less than 3MB!";
}
}
else
{
_fileName = null;
StatusLabel.Text = "Upload status: Only PDF or Word files are accepted!";
}
}
catch (Exception ex)
{
_fileName = null;
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
}
ASP.NET WebForms doesn't quite work like you expect it to... You have to understand the page life cycle.
Basically, at each request, your page object is recreated from scratch. The two button clicks will generate two requests, and so you'll get two page instances, one for each request. You can't share data between them this way.
You have several ways to overcome this:
Use the ViewState for this. This is an object that is basically serialized, then sent to the client. The client sends it back at each postback, and it's deserialized so you can access it. So do not put sensitive data inside. There are facilities that let you encrypt this data though.
Use the Session. But this can become messy pretty quick, and you'll have to deal with the case when the user opens serveral instances of the same page.

FileUpload.SaveAs issue

I am saving (uploading) file to FTP server using file upload control and .SaveAs method. But after 1st post back session values are lost. Not sure why and any work around this.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["TheUser"] != null)
{
aUser = (clsUser)Session["TheUser"];
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)//continue only if the file control has the file
{
if (Get_and_Show_FileInformation())//if the file information was retrived and loaded into the textboxes
{
//continue with the execution
}
else
{
//error message displyed
}
}
}
protected bool Get_and_Show_FileInformation()
{
if (FileUpload1.HasFile)
{
string fName = FileUpload1.PostedFile.FileName;
string extension = Path.GetExtension(fName);
string FileName = fName.Substring(0, fName.Length - extension.Length);
string dir = uname;
string appPath = Server.MapPath("Uploads/") + dir;
FileInfo MyFileInfo = new FileInfo(appPath);
DirectoryInfo newDirectoryInfo = new DirectoryInfo(appPath);
if (!Directory.Exists(appPath))//if user is uploading to FTP_Upload first time, create a new directory for him/her
{
try
{
FileUpload1.SaveAs(Server.MapPath("~/Uploads/" + dir + "/" + FileName)); // ERROR here, call to this .SaveAs method causes loss of session values (Session["TheUser"])
Image2.ImageUrl = "~/Uploads/" + dir + "/" + FileName;
return true;
}
catch (Exception ex)
{
lbl_Err.Text = "<br/>Error: Error creating and saving into your space!(Error Code:XF05)";
return false;
}
}
else
{
//same code but don't create the directory
}
}
}

How to give userchoice file name in browserdialog box

Hi in my windows form application i want to save some data in a folder and when user selcts the browse button it should browse to reqired folder and should consist of a textbox to enter the filename of user choice. How can i achieve this . The below code is not working for me
private void OutputFolder_button_Click(object sender, EventArgs e)
{
FolderBrowserDialog fd = new FolderBrowserDialog();
try
{
if (fd.ShowDialog() == DialogResult.OK)
{
if (string.IsNullOrEmpty(OutputFolder.Text))
{
MessageBox.Show(" Please provide output file to do backup ");
return;
}
outputFileName = fd.SelectedPath + "\\" + outputFileName;
File.Create(outputFileName).Dispose();
OutputFolder.Text = outputFileName;
//File.Create(outputFileName);
DisplayMainWindow("Selected path to backup" + outputFileName);
Logger.Log("Selected path to backup" + outputFileName);
}
}
catch (Exception ex)
{
MessageBox.Show("Exception" + ex);
}
Sounds like you need the SaveFileDialog class.
You need a SaveFileDialog.
The example in the MSDN page should be enough to get you started.

Categories