Image is not stored into Images folder after upload attempt. What's wrong with my code?
Here is my code:
protected void btnupload_Click(object sender, EventArgs e)
{
if (fileupload1.HasFile)
{
string fileName = fileupload1.FileName.ToString();
string uploadFolderPath = "~/Image/";
string filePath = HttpContext.Current.Server.MapPath(uploadFolderPath);
fileupload1.SaveAs(filePath + "\\" + fileName);
img1.ImageUrl = "~/Image/" + "/" + fileupload1.FileName.ToString();
lblimg_name.Text= fileupload1.FileName.ToString();
}
}
If you are using <asp:FileUpload>, try this:
Or Describe in detail
string strFileName = "fileName";
string strFileType = System.IO.Path.GetExtension(fileupload1.FileName).ToString().ToLower();
fileupload1.SaveAs(Server.MapPath("folderpath" + strFileName + strFileType));
Try this code..
protected void btnupload_Click(object sender, EventArgs e)
{
if (fileupload1.HasFile)
{
string fileName = Path.GetFileName(fileupload1.PostedFile.FileName);
fileupload1.PostedFile.SaveAs(Server.MapPath("~/Image/") + fileName);
}
}
change
img1.ImageUrl = "~/Image/" + "/" + fileupload1.FileName.ToString();
to
img1.ImageUrl = "~/Image/" + fileupload1.FileName;
you have additional "/" in your path
Related
My user can create a file name that goes to a specific directory path(Textbox3) and they can change the directory path(TextBox4), I am having trouble reading Textbox4 which is the changing the path textbox.
It reads textbox3 just fine and does everything i need it to do if there is a filename in the textbox but when i put something in textbox4 it is not reading it.
private void textBox3_TextChanged(object sender, EventArgs e) //reads fine, file goes to C:\\Temp
{
string textBoxContents = textBox3.Text;
}
private void textBox4_TextChanged(object sender, EventArgs e)//this is not required, this is only if they want to change where the file is going Ex:(D:\\Test
{
string textBoxContents = textBox4.Text;
}
private void button1_Click(object sender, EventArgs e)
{
string Filename = textBox3.Text.Substring(0) + ".txt";
string Filepath = textBox4.Text.Substring(0) + ".txt";
var files = Directory.GetFiles(#"C:\\Temp").Length;
string path2 = Path.GetFullPath("C:\\Temp");
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string var = Path.Combine(docPath, path2);
string var1 = Path.Combine(var, Filename);
using (StreamWriter objWriter = new StreamWriter(var1))
{
int numpins = int.Parse(textBox1.Text);
string basepin = textBox2.Text;
int pinlength = basepin.Length;
string formatspecifier = "{0:d" + pinlength.ToString() + "}" + "{1}";
long pinnumber = long.Parse(basepin);
string dig = textBox2.Text;
string result = GetCheckDigit(dig);
objWriter.WriteLine($"These are the Bin ranges");
objWriter.WriteLine();
for (int d = 0; d < numpins; d++)
{
if (String.IsNullOrEmpty(dig))
{
throw new Exception("null value not allowed");
}
else
{
dig = pinnumber.ToString();
result = GetCheckDigit(dig);
}
basepin = string.Format(formatspecifier, pinnumber, result);
objWriter.WriteLine(basepin);
pinnumber++;
}
objWriter.Close();
MessageBox.Show("File has been created");
}
}
Is there a much better way for me to streamWrite without needing to repeat the code for every button I press? Below is an example I am working on where one button does it's own thing and writes accordingly to vowels and the other does the same thing except it writes accordingly for no alpha characters:
private void btnVowels_Click(object sender, EventArgs e)
{
string wholeText = "";
string copyText = richTextBox1.Text;
if (System.IO.File.Exists(Second_File) == true)
{
System.IO.StreamWriter objWriter;
objWriter = new System.IO.StreamWriter(Second_File);
string vowels = "AaEeIiOoUu";
copyText = new string(copyText.Where(c => !vowels.Contains(c)).ToArray());
wholeText = richTextBox1.Text + copyText;
objWriter.Write(wholeText);
richTextBox2.Text = wholeText;
objWriter.Close();
}
else
{
MessageBox.Show("No file named " + Second_File);
}
}
private void btnAlpha_Click(object sender, EventArgs e)
{
string wholeText = "";
string copyText = richTextBox1.Text;
if (System.IO.File.Exists(Second_File) == true)
{
System.IO.StreamWriter objWriter;
objWriter = new System.IO.StreamWriter(Second_File);
string nonAlpha = #"[^A-Za-z ]+";
string addSpace = "";
copyText = Regex.Replace(copyText, nonAlpha, addSpace);
objWriter.Write(wholeText);
richTextBox2.Text = wholeText;
objWriter.Close();
}
else
{
MessageBox.Show("No file named " + Second_File);
}
}
You could use a common function that will take care of writing the contents to the file and updating the second textbox:
private void btnAlpha_Click(object sender, EventArgs e)
{
string nonAlpha = #"[^A-Za-z ]+";
string addSpace = "";
string copyText = richTextBox1.Text;
copyText = Regex.Replace(copyText, nonAlpha, addSpace);
WriteToFile(Second_File, wholeText);
}
private void btnVowels_Click(object sender, EventArgs e)
{
string vowels = "AaEeIiOoUu";
string copyText = richTextBox1.Text;
copyText = new string(copyText.Where(c => !vowels.Contains(c)).ToArray());
string wholeText = richTextBox1.Text + copyText;
WriteToFile(Second_File, wholeText);
}
private void WriteToFile(string filename, string contents)
{
if (File.Exists(filename))
{
File.WriteAllText(filename, contents);
richTextBox2.Text = wholeText;
}
else
{
MessageBox.Show("No file named " + filename);
}
}
why not doing it this way?
private void Write(string file, string text)
{
if (File.Exists(file))
{
using (StreamWriter objWriter = new StreamWriter(file))
{
objWriter.Write(text);
}
}
else
{
MessageBox.Show("No file named " + file);
}
}
private void btnAlpha_Click(object sender, EventArgs e)
{
string wholeText = "";
string copyText = richTextBox1.Text;
string nonAlpha = #"[^A-Za-z ]+";
string addSpace = "";
copyText = Regex.Replace(copyText, nonAlpha, addSpace);
wholeText = richTextBox1.Text + copyText;
Write(Second_File, wholeText); // same for the second button
richTextBox2.Text = wholeText;
}
I'm trying to use two Ajaxfileupload controls in the same page, but both enter the same uploadcomplete function and I have no idea why..
(They enter the "AjaxFileUpload1_UploadComplete" function)
here is my aspx part:
<asp:AjaxFileUpload ID="AjaxFileUpload1" runat="server" OnUploadComplete="AjaxFileUpload1_UploadComplete" ThrobberID="myThrobber" MaximumNumberOfFiles="10" AllowedFileTypes="jpg,jpeg"/>
<asp:AjaxFileUpload ID="AjaxFileUpload2" runat="server" OnUploadComplete="AjaxFileUpload1_prof_pic" ThrobberID="myThrobber" MaximumNumberOfFiles="1" AllowedFileTypes="jpg,jpeg"/>
and here is my code behind:
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
Directory.CreateDirectory(Server.MapPath("~/Member_Data/" + id + "/images/"));
string filePath = "~/Member_Data/" + id + "/images/";
string path = filePath + e.FileName;
AjaxFileUpload1.SaveAs(Server.MapPath(filePath) + e.FileName);
db1.insert_pic_slide(id, path);
string qstring = "?id=" + id;
//Response.Redirect("profile_layout.aspx" + qstring);
}
protected void AjaxFileUpload1_prof_pic(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
Directory.CreateDirectory(Server.MapPath("~/Member_Data/" + id + "/images/"));
string filePath = "~/Member_Data/" + id + "/images/";
string path = filePath + e.FileName;
AjaxFileUpload2.SaveAs(Server.MapPath(filePath) + e.FileName);
db1.insert_pic(id, path);
string qstring = "?id=" + id;
Response.Redirect("profile_layout.aspx" + qstring);
}
I was also faced the same problem, so just I removed the second Ajaxfileupload control , and I upload the files based on the dropdown selected value. I am just using single fileupload control.
Im trying to get my head around backgroundworker and the progressbar, so far i have got it to work but not exactly how i want it to work. Basically i am sorting/renaming folders and copying them to a different location, this works and the code is self explanatory, the output folders generated are as expected. However for each folder i intend to search through i have to right click it to get the number of files and then in the code i have to set the progressBar1.Maximum to that value in order for it to show the coreect progression of the progress bar. How is it possible to get this to set the number of files automatically since it goes through each folder anyway? Some folders have thousands of files and others have millions. beyond this i want to add a label so that it displays the name of the file it is processing along with the progressbar updates.
namespace Data_Sorter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnSelect_Click(object sender, EventArgs e)
{
folderBrowserDialog1.ShowDialog();
tbFilePath.Text = folderBrowserDialog1.SelectedPath.ToString();
}
private void btnSort_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
int totalFiles = 0;
foreach (var file in Directory.GetFiles(tbFilePath.Text, "*.txt", SearchOption.AllDirectories))
{
backgroundWorker1.ReportProgress(totalFiles);
string fullFilename = file.ToString();
string[] pathParts = fullFilename.Split('\\');
string date = pathParts[6];
string fileName = pathParts[7];
string[] partName = fileName.Split('_');
string point = partName[3];
Directory.CreateDirectory("Data Sorted Logs\\" + point + "\\" + date + "\\");
if (Directory.Exists(("Data Sorted Logs\\" + point + "\\" + date + "\\")))
{
string destPath = (point + "\\" + date + "\\");
File.Copy(fullFilename, "C:\\Documents and Settings\\PC\\Desktop\\Sorter\\Data Sorter\\bin\\Debug\\Data Sorted Logs\\" + destPath + fileName); }
else
{
MessageBox.Show("destination folder not found " + date + point);
}
totalFiles++;
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Done");
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Maximum = 6777; // set this value at the maximum number of files you want to sort //
progressBar1.Value = e.ProgressPercentage;
}
}
You can find out the file number simply reading the GetFiles length.
You can pass the relative percentage using the expression: (i * 100) / totalFiles, in this way it's not necessary to set the Maximum value for the progress.
You can also report the filename to the progressbar passing it as the UserState in the progressChanged event.
Try the code below:
namespace Data_Sorter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnSelect_Click(object sender, EventArgs e)
{
folderBrowserDialog1.ShowDialog();
tbFilePath.Text = folderBrowserDialog1.SelectedPath.ToString();
}
private void btnSort_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
int totalFiles = 0;
string[] files = Directory.GetFiles(tbFilePath.Text, "*.txt", SearchOption.AllDirectories);
totalFiles = files.Length;
int i = 0;
foreach (var file in files)
{
backgroundWorker1.ReportProgress((i * 100) / totalFiles, file);
i++
string fullFilename = file.ToString();
string[] pathParts = fullFilename.Split('\\');
string date = pathParts[6];
string fileName = pathParts[7];
string[] partName = fileName.Split('_');
string point = partName[3];
Directory.CreateDirectory("Data Sorted Logs\\" + point + "\\" + date + "\\");
if (Directory.Exists(("Data Sorted Logs\\" + point + "\\" + date + "\\")))
{
string destPath = (point + "\\" + date + "\\");
File.Copy(fullFilename, "C:\\Documents and Settings\\PC\\Desktop\\Sorter\\Data Sorter\\bin\\Debug\\Data Sorted Logs\\" + destPath + fileName); }
else
{
MessageBox.Show("destination folder not found " + date + point);
}
totalFiles++;
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Done");
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
progressBar1.Text = e.UserState.ToString();//or yourNewLabel.Text = e.UserState.ToString();
}
}
Move the call to GetFiles up so you can get the length of the array it returns:
string[] files = Directory.GetFiles(tbFilePath.Text, "*.txt",
SearchOption.AllDirectories));
// Note - you won't be able to set this UI property from DoWork
// because of cross-thread issues:
// progressbar1.Maximum = files.Length;
int fileCount = files.Length;
foreach (var file in files ...
i have a AsyncFileUpload control :
<asp:AsyncFileUpload ID="venfileupld" runat="server" OnUploadedComplete="ProcessUpload" />
on its OnUploadedComplete event i am writing this code :
protected void ProcessUpload(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string name = venfileupld.FileName.ToString();
string filepath = "upload_excel/" + name;
venfileupld.SaveAs(Server.MapPath(name));
}
now i have to read the content of the uploaded file ... i have a function for that:
public void writetodb(string filename)
{
string[] str;
string vcode = "";
string pswd = "";
string vname = "";
StreamReader sr = new StreamReader(filename);
string line="";
while ((line = sr.ReadLine()) != null)
{
str = line.Split(new char[] { ',' });
vcode = str[0];
pswd = str[1];
vname = str[2];
insertdataintosql(vcode, pswd, vname);
}
lblmsg4.Text = "Data Inserted Sucessfully";
}
now my query is that how i can get the uploaded file to pass to this function ?
UPDATE
i have done this :
protected void ProcessUpload(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string name = venfileupld.FileName.ToString();
string filepath = "upload_excel/" + name;
venfileupld.SaveAs(Server.MapPath(name));
string filename = System.IO.Path.GetFileName(e.FileName);
writetodb(filepath);
}
but getting an error... file not found
I'm not sure if i have understood the problem, but isn't it easy as:
protected void ProcessUpload(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string name = System.IO.Path.GetFileName(e.filename);
string dir = Server.MapPath("upload_excel/");
string path = Path.Combine(dir, name);
venfileupld.SaveAs(path);
writetodb(path);
}
SaveAs will save the file on the server, so you can do what you want with it afterwards.