I get the problem newline in constant:
protected void UploadButton_Click(object sender, EventArgs e)
{
string theUserId = Session["UserID"].ToString();
if (FileUploadControl.HasFile)
{
try
{
string filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~/userdata/"+theUserId+"/uploadedimage/) + filename);
//here
StatusLabel.Text = "Upload status: File uploaded!";
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
}
Im also wondering is there a way I can resize the image upon upload if so, how?
And as this is a save as in my fileupload control will this overwrite any folder that has the userid already there? (what I want and need)
Newline in constant
FileUploadControl.SaveAs(Server.MapPath("~/userdata/"+theUserId+"/uploadedimage/) + filename);
//here
Should be:
FileUploadControl.SaveAs(Server.MapPath("~/userdata/"+theUserId+"/uploadedimage/") + filename);
//here
Image resize / thumbnails
If it's a thumbnail image you're after, then you can use Image.GetThumbnailImage. A basic implementation is like this:
using (System.Drawing.Image fullsizeImage =
System.Drawing.Image.FromFile(originalFilePath))
{
// these calls to RotateFlip aren't essential, but they prevent the image
// from using its built-in thumbnail, which is invariably poor quality.
// I like to think of it as shaking the thumbnail out ;)
fullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
fullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
using (System.Drawing.Image thumbnailImage =
fullsizeImage.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero))
{
thumbnailImage.Save(newFilePath);
}
}
Overwrite
Overwrite is the default behaviour, so uploading the same file to the same UserID will replace it.
Well I can already see in the line above your error you are missing a quote after /uploadedimage/ and the next to last paren should be after filename not /uploadedimage/
Are you missing a quote or is it a typo:
Server.MapPath("~/userdata/"+theUserId+"/uploadedimage/")
I would also recommend using string.Format when using lots of string concatenation (usually do this when I have to use + more than once):
Server.MapPath(string.Format("~/userdata/{0}/uploadedimage/", theUserId))
EDIT: to answer resize comment:
Here is a link to a similar SO question:
how to resize an image whileing saving in an folder
Which value has the newline variable?
Below adds a Trim() to the value collected and also provides a way to see what each of the string values collected afterwards are.
protected void UploadButton_Click(object sender, EventArgs e)
{
string theUserId = Session["UserID"].ToString().Trim(); // add Trim()
if (FileUploadControl.HasFile && !String.IsNullOrEmpty(theUserId)) // add test
{
try
{
string filename = Path.GetFileName(FileUploadControl.FileName);
Console.WriteLine(filename);
string filepath = string.Format("~/userdata/{0}/uploadedimage/", theUserId);
Console.WriteLine(filepath );
string mapPath = Server.MapPath(filepath);
Console.WriteLine(mapPath );
FileUploadControl.SaveAs(mapPath + filename);
StatusLabel.Text = "Upload status: File uploaded!";
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
Just Trim() the string value has the newline constant in it.
Related
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUploadControl.HasFile)
{
try
{
string filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~/Files/") + filename);
StatusLabel.Text = "Upload status: File uploaded!";
String x = Server.MapPath("~/Files/") + filename;
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
In this simple example, when I try file that is under 1MB, it works well, but if I try 10MB, i get "This site can’t be reached The connection was reset." Which is browser message.
So where's the problem?
Check your web.config file (10mb and 5 minutes):
<system.web>
<httpRuntime maxRequestLength="102400" executionTimeout="300"/>
</system.web>
I'm creating dataset from csv excel file and that files is processing while I access it.
It says "
I need to access it read only mode? This is working code.
private void connect()
{
try
{
if (checkbox1.Checked == false)
{
FilePath = #"C:\FILE";
}
else
{
FilePath = #"\\192.168.0.2\file\"; //
}
strConn = #"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" + FilePath + #"\;Extensions=csv,txt";
Connect = new OdbcConnection(strConn);
Connect.Open();
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
DataGrid1.SelectAll();
DataGrid1.ClearSelection();
FileName = ".csv";
CSVDataSource = FilePath + FileName;
ReadData(FileName);
DataGrid1.Update();
}
It says it cannot open the file '(unknown)'. The thing about exclusive and permissions is probably just a too general error description. You do not seem to have a valid file path, also you might not be able to open it directly from a network path.
Verify your file path, and if it still not works - copy it to your local machine and try again.
I have a simple program here wherein I can create a folder then save the an image to the folder created. The folder gets successfully created but I'm getting error into saving it to the newly created file. The error is:
The file could not be uploaded. The following error occured: 'N:/Kim's New Project/Safety Accident Report/File Uploader 2/File
Uploader 2/Uploads/asdsa' is a physical path, but a virtual path was
expected.
Can you please check my code. Please help. Thank you.
protected void button1_Click(object sender, EventArgs e)
{
if (FileUpload2.HasFile)
{
try
{
if (FileUpload2.PostedFile.ContentType == "image/jpeg")
{
if (FileUpload2.PostedFile.ContentLength < 512000)
{
string strpath = #"N:\Kim's New Project\Safety Accident Report\File Uploader 2\File Uploader 2\Uploads\" + txtName.Text;
if (!(Directory.Exists(strpath)))
{
Directory.CreateDirectory(strpath);
lblResult.Text = "Directory Created";
if ((Directory.Exists(strpath)))
{
string filename = Path.GetFileName(FileUpload2.FileName);
FileUpload2.SaveAs(Server.MapPath(strpath) + filename);
Label1.Text = "File uploaded successfully!";
}
}
else
{
lblResult.Text = "Already Directory Exists with the same name";
}
}
else
Label1.Text = "File maximum size is 500 Kb";
}
else
Label1.Text = "Only JPEG files are accepted!";
}
catch (Exception exc)
{
Label1.Text = "The file could not be uploaded. The following error occured: " + exc.Message;
}
}
Instead of
FileUpload2.SaveAs(Server.MapPath(strpath) + filename);
try
FileUpload2.SaveAs(Path.Combine(strPath, filename));
you already know the physical save path - no need for Server.MapPath
Try..
string strpath = Server.MapPath("~/Test");
if (!(Directory.Exists(strpath)))
{
Directory.CreateDirectory(strpath);
}
The following code works when I work with CSV files under 1MB but fails when I try to read 600MB file. Any reason why? Or any fixes?
What I am trying to do is read a large raw CSV file in Visual C# 2010 and manipulate the contents, could be line by line or to memory at one go and export 5 files with certain selections using LINQ. These 5 files are to be used in various processes so need them to be split into 5 different files with very different content.
When the file is small the codes work perfect but when it's too big it gives me the messagebox from Exception handling "Cannot write to source destination". I have tried both ReadAllLines() and ReadLines() Please could you advise me. Thanks.
public void button2_Click(object sender, EventArgs e)
{
string file_name = textBox1.Text.ToString();
// Get the directories to split the file in.
string directoryPath = Path.GetDirectoryName(textBox1.Text.ToString());
if (File.Exists(file_name) == true)
{
try
{
StreamReader readerfile = new StreamReader(file_name);
var BillSummaryQuery1 =
(from line in File.ReadAllLines(file_name)
let linerecord = line.Split(',').ToList()
select line).ToList();
#region Start Writing BillSummary.CSV
//lines removed
#endregion End writing BillSummary.CSV
#region Start writing Notes.CSV
//lines removed
#endregion Notes.CSV
string message =
"Bill Translated Successfully! \r\nFiles located in: " + directoryPath;
MessageBox.Show(message, "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception)
{
string message2 = "Cannot write to source destination";
MessageBox.Show(message2, "Error");
}
}
else
{
MessageBox.Show("No such file exists","Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
If you are using a StreamReader, why don't use it ?
public void button2_Click(object sender, EventArgs e)
{
string file_name = textBox1.Text.ToString();
// Get the directories to split the file in.
string directoryPath = Path.GetDirectoryName(textBox1.Text.ToString());
if (File.Exists(file_name) == true)
{
try
{
using (StreamReader reader= new StreamReader(file_name))
{
string line = null;
while ((line = reader.ReadLine()) != null)
{
// Do your stuff
}
}
}
catch (Exception ex)
{
Trace.TraceError(ex.Message);
string message2 = "Cannot write to source destination";
MessageBox.Show(message2, "Error");
}
}
else
{
MessageBox.Show("No such file exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Rolling your own CSV reader is a waste of time unless the files that you're reading are guaranteed to be very simple. Use a pre-existing, tried-and-tested implementation instead.
I have a form which has radiobuttons, each of them is giving a file name in a string, and what I want to do is to have that string as a name for any file that a user uploads.
It'll be great if you could explain to me how to rename, because I already got it the code to upload or just help me modify this function, I would probably have to add to the parameters "string type" tho:
public void uploadFTP(string filename, string type, string password, ProgressBar progressbar)
{
WebClient client = new WebClient();
client.Credentials = new System.Net.NetworkCredential("username", password);
try
{
client.UploadFileAsync(new Uri(#"ftp://ftpaddress.com" + "/" + new FileInfo(filename).Name), "STOR", filename);
}
catch(System.InvalidCastException)
{
// Handled it
}
catch (System.ArgumentException)
{
// Handled it
}
client.UploadProgressChanged += (s, e) =>
{
progressbar.Value = e.ProgressPercentage;
};
client.UploadFileCompleted += (s, e) =>
{
MessageBox.Show("Upload complete", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
};
}
If it's important: The files are RTF (RichTextBox).
Thanks!
Just upload to different URL then. Replace new FileInfo(filename).Name in your code with the name you actually want. Also, I think not using string manipulation is better. And the STOR command is the default.
client.UploadFileAsync(new Uri(new Uri("ftp://ftpaddress.com"), newName)), filename);