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.
Related
I am new to C#. I am working on a Windows Form that should do the following:
Browse files on local drive
Allow the user to select files
List the selected files in a listBox
Allow the user to input a new file name and, when they click the rename button, it renames the selected file in the ListBox.
I am not able to do step 4 as the new text is changed in the listBox but the actual file name is still the same in folder. How can I do that? I have listed below the Form.cs
Thank you.
public partial class everSupportForm : Form
{
private void buttonSelect_Click(object sender, EventArgs e)
{
System.IO.Stream myStream;
var myDialog = new OpenFileDialog();
myDialog.InitialDirectory = #"c:\";
myDialog.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
// + "Images (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|" //If you want to add filters for browsing only images.
myDialog.FilterIndex = 1;
myDialog.RestoreDirectory = true;
myDialog.Multiselect = true;
myDialog.Title = "Please Select File(s) to Rename";
if (myDialog.ShowDialog() != DialogResult.OK) return;
{
foreach (var file in myDialog.FileNames)
{
try
{
if ((myStream = myDialog.OpenFile()) != null)
{
using (myStream)
{
outputListBox.Items.Add(System.IO.Path.GetFileName(file));
}
}
}
catch (Exception ex)
{
// Could not load File specifying the causes
MessageBox.Show("Cannot display the File");
}
}
}
}
private void buttonExit_Click(object sender, EventArgs e) => Application.Exit();
// Removes a selected item
private void buttonRemove_Click(object sender, EventArgs e)
{
if (outputListBox.SelectedIndex >= 0)
outputListBox.Items.RemoveAt(outputListBox.SelectedIndex);
}
// Clears the listed images ListBox
private void buttonClear_Click(object sender, EventArgs e) => outputListBox.Items.Clear();
private void buttonRename_Click(object sender, EventArgs e)
{
if (outputListBox.SelectedIndex >= 0)
outputListBox.Items[outputListBox.SelectedIndex] = newNametextBox.Text;
else MessageBox.Show("There is no Files in the Above list to be Selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
First of all, you have a problem here.
You're adding the files names using Path.GetFileName, so you won't have the files paths anymore => you can't rename them.
Solution 1 - Adding the paths to the listbox
You simple remove the Path.GetFileName and in when the rename button is clicked, you use an InputBox to ask the user for the new file name:
N.B: Add a reference to Microsoft.VisualBasic, InputBoxis in the Microsoft.VisualBasic.Interaction namespace.
private void buttonRename_Click(object sender, EventArgs e)
{
if (outputListBox.SelectedIndex >=0)
{
string fileToRename = outputListBox.Items[outputListBox.SelectedIndex].ToString();
string newFileName = InputBox("Please enter the new file's name:", "Rename file", "Default value");
if (!string.IsNullOrEmpty(newFileName))
{
string fileName = Path.GetFileName(fileToRename);
string newFilePath = fileToRename.Replace(fileName, newFileName);
System.IO.File.Move(fileToRename, newFilePath);
outputListBox.Items[outputListBox.SelectedIndex] = newFilePath;
}
}
else
{
MessageBox.Show("There is no Files in the Above list to be Selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Solution 2 -- Keep a seperate list containing the paths
The concept is the same as the first solution, but instead of adding the file paths to your listbox, you add the file names but you keep a seperate list of paths that is synced with your listbox.
Meaning that, if you modify the listbox, modify the list of paths.
After that you can access the file paths using the listbox's SelectedIndex (since they are synced).
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());
}
}
I am using DropNet. I have problem with upload file into DropBox.
I am sure the connection with dropbox in fine. when I changed the method of upload to create file and delete file method that works fine.
I really can not see any problem that why is not uploading? I use exactly same API as DropNet.
protected void Btn_upload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
if (Session["DropNetUserLogin"] != null)
{
try
{
_client.UseSandbox = true;
_client.UploadFile("/", FileUpload1.FileName, FileUpload1.FileBytes);
}
catch (Exception ex)
{
litOutput.Text = "Error in upload user login in session " + ex.Message;
}
}
else
{
litOutput.Text = "Session expired...";
}
}
else
{
litOutput.Text = "You did not specify a file to upload.";
}
}
}
Here is code which worked for me, hoping that this may help you:
private void button1_Click(object sender, RoutedEventArgs e)
{
var dlg = new OpenFileDialog();
dlg.Filter = "Text documents (.txt)|*.txt";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
string filename = dlg.FileName;
FileNameTextBox.Text = filename;
}
var x = #"/" + Path.GetFileName(FileNameTextBox.Text);
_client.UploadFile("/", Path.GetFileName(FileNameTextBox.Text), File.ReadAllBytes(#"" + FileNameTextBox.Text));
}
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
}
}
}
Hey Everyone,
Sorry to bother you with this, but I'm having an issue with selecting multiple xlsx files through a file browser window in a winforms application when debugging and can't figure out what I did wrong.
Problem: I set Multiselect=true under the OpenFileDialog but I still cannot select more than one file.
What do I need to change to get the multiSelect feature to work?
Do I need to add anything under sourceFileOpenFileDialog method?
Do I need to add anything under listBoxSourceFiles_SelectedIndexChanged method to get the filenames to load correclty in the listbox?
// When the user clicks on Select Files Button, this happens
private void sourceFiles_Click(object sender, EventArgs e)
{
Stream myStream;
int i = 0;
OpenFileDialog sourceFileOpenFileDialog = new OpenFileDialog();
this.sourceFileOpenFileDialog.InitialDirectory = "i:\\CommissisionReconciliation\\Review\\";
this.sourceFileOpenFileDialog.Filter = "Excel Files (*.xls;*.xlsx;)|*.xls;*.xlsx;|" + "All Files (*.*)|*.*";
this.sourceFileOpenFileDialog.FilterIndex = 2;
this.sourceFileOpenFileDialog.RestoreDirectory = true;
this.sourceFileOpenFileDialog.Multiselect = true;
this.sourceFileOpenFileDialog.Title = "Please Select Excel Source File(s) for Consolidation";
if (sourceFileOpenFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = sourceFileOpenFileDialog.OpenFile()) != null)
{
using (myStream)
{
foreach (string FileName in sourceFileOpenFileDialog.FileNames)
{
sourceFileOpenFileDialog.FileNames[i] = FileName;
listBoxSourceFiles.Items.Add(FileName);
Log("Source Files: " + sourceFileOpenFileDialog.FileNames[i]);
i++;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
//method for the listbox. Do I need anything here?
private void listBoxSourceFiles_SelectedIndexChanged(object sender, EventArgs e)
{
}
//method for the sourceFileOpenFileDialog. Do I need anything here?
private void sourceFileOpenFileDialog_FileOk(object sender, CancelEventArgs e)
{
}
I updated the code to reflect sourceFileOpenFileDialog and the MultiSelect or Title doesn't work... Perhaps I'm referencing the onfiledialog wrong? is this the proper prefix to use?
Thanks for looking!
You are using two OpenFileDialogs. You display sourceFilesList but you initialized sourceFileOpenFileDialog. Using consistent naming rules religiously is a great way to avoid bugs like these btw.
Next problem, what is OpenFile() supposed to do when you selected more than one file? What is myStream actually used for?
You are setting up sourceFileOpenFileDialog but then use sourceFileList!!! Make up your mind and only use one.
Fixed the non-working MultiSelect by:
Updating the code to only use one variable sourceFileOpenFileDialog throughout the method and the MultiSelect or Title didnt work...
Removing all references to myStream. myStream was used in an example which i based my code off but i took it out and the multiSelect works!
Here's the working code:
// When the user clicks on Select Files Button, this happens
private void sourceFiles_Click(object sender, EventArgs e)
{
Stream myStream;
int i = 0;
OpenFileDialog sourceFileOpenFileDialog = new OpenFileDialog();
this.sourceFileOpenFileDialog.InitialDirectory = "i:\\CommissisionReconciliation\\Review\\";
this.sourceFileOpenFileDialog.Filter = "Excel Files (*.xls;*.xlsx;)|*.xls;*.xlsx;|" + "All Files (*.*)|*.*";
this.sourceFileOpenFileDialog.FilterIndex = 2;
this.sourceFileOpenFileDialog.RestoreDirectory = true;
this.sourceFileOpenFileDialog.Multiselect = true;
this.sourceFileOpenFileDialog.Title = "Please Select Excel Source File(s) for Consolidation";
if (sourceFileOpenFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
string tempFolder = System.IO.Path.GetTempPath();
foreach (string FileName in this.sourceFileOpenFileDialog.FileNames)
{
this.sourceFileOpenFileDialog.FileNames[i] = FileName;
listBoxSourceFiles.Items.Add(FileName);
Log("Source Files: " + sourceFileOpenFileDialog.FileNames[i]);
i++;
System.IO.File.Copy(FileName, tempFolder + #"\" + FileName);
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
//method for the listbox. Do I need anything here?
private void listBoxSourceFiles_SelectedIndexChanged(object sender, EventArgs e)
{
}
//method for the sourceFileOpenFileDialog. Do I need anything here?
private void sourceFileOpenFileDialog_FileOk(object sender, CancelEventArgs e)
{
}