Hi I am trying to refer a variable in different scopes i.e in a different method. I am doing this by using getter and setter but the variable in a different method is coming as null. I saw a related problem here but this too is not working C# referencing a variable from another method. Here is my code:
private string FileName { get; set; }
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
FileName = FileUpload1.FileName.ToString();
string extension = Path.GetExtension(FileName);
FileName = FileName.Replace(extension, "");
if (extension.ToLower()==".pdf")
{
FileUpload1.SaveAs(Server.MapPath("~/Uploads/" + FileName));
}
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
string saveLocation = Server.MapPath("~/Downloads/" + FileName + ".doc");
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AppendHeader("content-disposition", "attachment;fileName" + Filename);
Response.WriteFile(saveLocation);
Response.End();
}
while I am running this the FileName is coming as NULL. Though it is a property and a class variable.
Another even is basically a logic for downloading a file at saveLocation. What I could be missing?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Each of these methods are called upon separate requests to your application, one for each button click. Each request will create a new instance of your page class, meaning the property will be re-initialized (in this case, the default value of string, which is null).
In order to keep the value around, you’ll need to put it somewhere that can persist between requests but be distinct to the user. We have just such a place in the Session object.
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fileName = FileUpload1.FileName.ToString();
string extension = Path.GetExtension(fileName);
fileName = fileName.Replace(extension, "");
if (extension.ToLower()==".pdf")
{
FileUpload1.SaveAs(Server.MapPath("~/Uploads/" + fileName));
}
Session["UploadedFileName"] = fileName;
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
string fileName = Session["UploadedFileName"];
if (string.IsNullOrWhiteSpace(fileName))
{
// you may want to throw and exception or display an error message here...
// At minimum, don't try to send the file
return;
}
string saveLocation = Server.MapPath("~/Downloads/" + fileName + ".doc");
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AppendHeader("content-disposition", "attachment;fileName" + Filename);
Response.WriteFile(saveLocation);
Response.End();
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0