i am trying to upload documents .user can be able to upload theri documents but he/she can be upload images istead of documents and i want to d restrict about this how to apply condition this is my upload code
if (FileUploadControl.PostedFile != null &&
FileUploadControl.PostedFile.ContentLength
> 0)
{
if
(FileUploadControl.FileContent.Length < 100000)
{
string filename =
Path.GetFileName(FileUploadControl.PostedFile.FileName);
string folder = Server.MapPath("~/Docfiles/");
Directory.CreateDirectory(folder);
FileUploadControl.PostedFile.SaveAs(Path.Combine(folder, filename));
try
{
cc.upload1(Txt_docde.Value, txt_dname.Value,
FileUploadControl.FileName, Convert.ToInt32(Docdrop.SelectedValue),
Convert.ToInt32(DropDownList2.SelectedValue),
Convert.ToString(Session["Login2"]),Convert.ToInt32(Session["UserID"]));
StatusLabel.ForeColor = System.Drawing.Color.Green;
//StatusLabel.ForeColor = System.Drawing.FontStyle.Bold;
StatusLabel.Text = "Success";
}
catch
{
StatusLabel.ForeColor = System.Drawing.Color.Red;
Label2.Text = "Failed";
}
}
else
{
StatusLabel.ForeColor = System.Drawing.Color.Red;
Label2.Text = "File Size to big";
}
}
Make generic list of extensions you want to allow and then check if file you are trying to upload meets that extension requirement.
var allowedExtensions = new string[] { "doc", "docx", "pdf" };
var extension = Path.GetExtension(FileUploadControl.PostedFile.FileName).ToLower().Replace(".", "");
if (allowedExtensions.Contains(extension))
{
// Good to go
}
Here is full code for you
if (FileUploadControl.PostedFile != null && FileUploadControl.PostedFile.ContentLength > 0)
{
var allowedExtensions = new string[] { "doc", "docx", "pdf" };
var extension = Path.GetExtension(FileUploadControl.PostedFile.FileName).ToLower().Replace(".", "");
if (FileUploadControl.FileContent.Length < 100000 && allowedExtensions.Contains(extension))
{
string filename =
Path.GetFileName(FileUploadControl.PostedFile.FileName);
string folder = Server.MapPath("~/Docfiles/");
Directory.CreateDirectory(folder);
FileUploadControl.PostedFile.SaveAs(Path.Combine(folder, filename));
try
{
cc.upload1(Txt_docde.Value, txt_dname.Value, FileUploadControl.FileName, Convert.ToInt32(Docdrop.SelectedValue), Convert.ToInt32(DropDownList2.SelectedValue), Convert.ToString(Session["Login2"]),Convert.ToInt32(Session["UserID"]));
StatusLabel.ForeColor = System.Drawing.Color.Green;
StatusLabel.Text = "Success";
}
catch
{
StatusLabel.ForeColor = System.Drawing.Color.Red;
Label2.Text = "Failed";
}
}
else
{
StatusLabel.ForeColor = System.Drawing.Color.Red;
Label2.Text = "File Size to big";
}
}
Try something like this to validate the file type suffix that you are interested in:
if (string.Equals(fileExt, ".pdf", StringComparison.OrdinalIgnoreCase)) {...}
You need to either check the extension of the posted file or its MIME type to detect whether it's the right format.
Go get the MIME type, check the ContentType property.
ASP.NET How to get MIME Type
If you want to look for a specific file type you can use the Path.GetExtension method.
string fileExtension = Path.GetExtension(filename);
if (fileExtension == ".doc") //or whatever file type your looking for
{
try
{ do your work }
}
Related
I've been trying to figure out how to use the SaveFileDialog function in c# to save more than one file at a time.
The basic idea is, after the user has set parameters for a .cfg file, the user types out a set of serial numbers for which to save the configuration as. Then a SaveFileDialog is called allowing the user to save the one .cfg file under the names of the serial numbers the user listed.
Is this possible to do? Do you need to put the function into a loop, or is there another way to achieve this goal?
the .cfg file is set up like:
timezone=1
auto_DST=1
location=0
alarm_time=21
alarm_seconds_P=0
etc.
Here is what I have so far for saving that file:
List<Parameter> _paramList = new List<Parameter>();
List<Information> _infoList = new List<Information>();
saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
saveFileDialog1.DefaultExt = ".CFG";
saveFileDialog1.FileName = ( "config_" + txtParamValue.Text);
saveFileDialog1.Filter = "Configuration files (*.CFG)|*.CFG|All files (*.*)|*.*";
if ( saveFileDialog1.ShowDialog( ) == DialogResult.OK )
{
using ( StreamWriter objWriter = new StreamWriter( saveFileDialog1.FileName ) )
{
foreach (Parameter p in _paramList)
{
String name = p.ParameterName.Trim();
String val = p.ParameterValue.Trim();
foreach (Information i in _infoList)
{
if (p.ParameterName.Trim() == i.SimpleName)
{
name = i.InfoName;
if (i.InputChoice == "1")
{
if (p.ParameterValue == "On")
val = "1";
else
val = "0";
}
break;
}
else if (p.ParameterName.Trim() == i.InfoName)
{
if (p.ParameterValue == "On")
val = "1";
else
val = "0";
break;
}
}
if (name == "location" && val != location_update)
{
name = "location_update";
}
objWriter.WriteLine(name + "=" + val);
}
objWriter.Close();
}
}
I'm searching in files. And depending on the extension I type in textBox2 that the files types I want to search in. For example if I typed in the textBox2 .txt it will search all text files. But I don't want to type .cs or .txt I want to type only cs or only txt
string restrictedFile = "";
List<string> restrictedFiles = new List<string>();
int numberofrestrictedFiles = 0;
int numberoffiles = 0;
IEnumerable<string> SearchAccessibleFilesNoDistinct(string root, List<string> files,BackgroundWorker worker, DoWorkEventArgs e)
{
_busy.WaitOne();
if (files == null)
files = new List<string>();
if (Directory.Exists(root))
{
foreach (var file in Directory.EnumerateFiles(root))
{
if (worker.CancellationPending == true)
{
e.Cancel = true;
return files;
}
restrictedFile = file;
string ext = Path.GetExtension(file);
if (!files.Contains(file) && ext == textBox2.Text)
{
files.Add(file);
}
numberoffiles++;
label24.Invoke((MethodInvoker)delegate
{
label24.Text = numberoffiles.ToString();
label24.Visible = true;
});
}
foreach (var subDir in Directory.EnumerateDirectories(root))
{
if (worker.CancellationPending == true)
{
e.Cancel = true;
return files;
}
try
{
SearchAccessibleFilesNoDistinct(subDir, files,worker, e);
}
catch (UnauthorizedAccessException)
{
restrictedFiles.Add(restrictedFile);
numberofrestrictedFiles++;
label11.Invoke((MethodInvoker)delegate
{
label11.Text = numberofrestrictedFiles.ToString();
label11.Visible = true;
});
continue;
}
}
}
return files;
}
At this part I'm getting the file extension and check if in the textBox2 it's the same. But since the file extension is .txt or .cs or .gif I have to type in the textBox2 also with '.' and instead I want to be able to type only cs gif txt....
Another sub question, How can I make that it will search in all any of files extension ? For example if I type in the textBox2 he string ALL or maybe . so it will search all the extensions.
EnumerateFiles has a prototype that accepts a search filter. It is more efficient to let the operating system filter the files than to filter them in code yourself.
To get files with a particular extension, search like this:
EnumerateFiles(root, "*." + extension);
To get all files, use this:
EnumerateFiles(root, "*.*");
To cover both cases, you could use:
var extension = Textbox2.Text;
if (string.IsNullOrWhitespace(extension)) extension = "*.*";
foreach (var file in Directory.EnumerateFiles(root, extension)
{
//etc....
Path.GetExtension returns the extension with the . (.docx), so you can change your if criteria to add this automatically:
if (!files.Contains(file) && ext == "." + textBox2.Text)
ok what im trying to do is load a text file search it for a certain string if the string exists then it will will disable button
if it don't exist it will Wright to the file
if (File.Exists(hostfile))
{
{
string s = "elfenliedtopfan5 programupdate";
string file = hostfile;
List<string> lines = new List<string>(System.IO.File.ReadAllLines(file));
int index = lines.FindLastIndex(item => item.Contains("elfenliedtopfan5 programupdate"));
if (index != -1)
{
lines.Insert(index + 1, s);//""
}
// System.IO.File.WriteAllLines(file, lines);
MessageBox.Show("text test 1 found");
}
}
else
{
DialogResult dialogResult = MessageBox.Show("text not found would you like to add it ", "Text Not Found", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
using (StreamWriter sw = File.AppendText(hostfile))
{
sw.WriteLine("elfenliedtopfan5 update");
sw.Close();
messagebox.show("done");
}
}
}
but even know it does exist it will add it again and im confused to why this is the case any help would be appropriated
elfenliedtopfan5
Here is a simple way to read from or write to a text file:
string filename=#"D:\file.txt";
string value="your value"
var content = System.IO.File.ReadAllText(filename);
if (content.Contains(value))
this.Button1.Enabled = false;
else
System.IO.File.AppendAllLines(filename, new string(){value} );
I am trying to develop upload file function with security as my programming instructor asked me to do. I implemented it in such a way that it will check the size, file format and the existence of the file. The logic was working well except for checking the existence of the file. For example, when I tried to upload a file which is already existed, I will not get a message telling me that the file is already existed and I don't know why it is not working.
protected void UploadFile(object sender, EventArgs e)
{
if(FileUpload1.HasFile)
try
{
string[] validTypes = { "bmp", "gif"};
string ext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
if (size < limit)
{
for (int i = 0; i < validTypes.Length; i++)
{
if (ext == "." + validTypes[i])
{
string path = #"~\Images\";
string comPath = Server.MapPath(path + "\\" + FileUpload1.FileName);
if (!File.Exists(comPath))
{
FileUpload1.PostedFile.SaveAs(comPath);
Label1.Text = "File uploaded";
}
else
{
Label1.Text = "Existed";
}
}
else
{
Label1.Text = "Invalid File." + string.Join(",", validTypes);
}
}
}
else
{
Label2.ForeColor = System.Drawing.Color.Red;
Label2.Text = "file is heavy";
}
}
catch (Exception ex)
{
Label2.Text = "The file could not be uploaded. The following error occured: " + ex.Message;
}
}
When I debugged the code, I found that it will execute the else statement, but instead of displaying it to the user, it will display the message in the outer else statement which is "Invalid File.". Why?
if (ext == "." + validTypes[i])
{
string path = #"~\Images\";
string comPath = Server.MapPath(path + "\\" + FileUpload1.FileName);
if (!File.Exists(comPath))
{
FileUpload1.PostedFile.SaveAs(comPath);
Label1.Text = "File uploaded";
}
else
{
Label1.Text = "Existed";
}
}
else
{
Label1.Text = "Invalid File." + string.Join(",", validTypes);
}
Also, my instructor told me that the following line causes a vulnerability called path traversal.
string path = #"~\Images\";
So how to prevent this security hole? ?Any ideas?
There is logical problem in you code.In the block
for (int i = 0; i < validTypes.Length; i++)
It will always run two time for each file.
What you can do you take a Boolean variable at set it to false.
Go inside the loop and if file found set boolean to true and use break statement.
At the end of loop check for the Boolean value and code accordingly.
Edit-1
Rather than looping through the array you can use like this
string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
int pos = Array.IndexOf(stringArray, value);
if (pos >- 1)
{
// the array contains the string and the pos variable
// will have its position in the array
}
In your case
string[] validTypes = { "bmp", "gif"};
string ext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
int pos = Array.IndexOf(validTypes , ext );
if(pos>=0)
{
string path = #"~\Images\";
string comPath = Server.MapPath(path + "\\" + FileUpload1.FileName);
if (!File.Exists(comPath))
{
FileUpload1.PostedFile.SaveAs(comPath);
Label1.Text = "File uploaded";
}
else
{
Label1.Text = "Existed";
}
}
else
{
Label1.Text = "Invalid File." + string.Join(",", validTypes);
}
string Newfilename;
string Defaultfilename;
protected void btnup_Click(object sender, EventArgs e)
{
if (ASPxUploadControl1.HasFile)
{
string fileExt =
Path.GetExtension(ASPxUploadControl1.FileName);
if (fileExt == ".xls" || fileExt == ".xlsx")
try
{
string extension = Path.GetExtension(ASPxUploadControl1.FileName);
string id = Guid.NewGuid().ToString();
string fileLocation = string.Format("{0}/{1}{2}", Server.MapPath("upload/"), id, extension);
ASPxUploadControl1.SaveAs( fileLocation );
StatusLabel.Text = "Upload status: File uploaded!";
Newfilename = fileLocation;
Defaultfilename = Path.GetFileName(ASPxUploadControl1.FileName);
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
else
{
StatusLabel.Text = "Please choose excel file";
}
}
}
I am trying to assign values to Newfilename and Defaultfilename (inside "try", after naming uploaded file), but they stay empty.
Where I'm wrong?
Refactor your code and think about the process that you want .. then Debug the Code.. Test it.. and if you have an Issue then edit your post.. that's what I suggest..
If statements should be wrapped with in a code block "{ }" same way that you have Try {} a good rule of thumb for even readability would be to wrap everthing around {} if you have If Else otherwise it makes if hard to read as well as lend assistance.
inside your code where you are declaring the following, make them variables within the method itself
string fileExt = string.Empty;
string extension = string.Empty;
string id = string.Empty;
string fileLocation = string.Empty;
so your method would look like this
protected void btnup_Click(object sender, EventArgs e)
{
string fileExt = string.Empty;
string extension = string.Empty;
string id = string.Empty;
string fileLocation = string.Empty;
if (ASPxUploadControl1.HasFile)
{
fileExt = Path.GetExtension(ASPxUploadControl1.FileName);
if (fileExt == ".xls" || fileExt == ".xlsx")
{
try
{
extension = Path.GetExtension(ASPxUploadControl1.FileName);
id = Guid.NewGuid().ToString();
fileLocation = string.Format("{0}/{1}{2}", Server.MapPath("upload/"), id, extension);
ASPxUploadControl1.SaveAs( fileLocation );
StatusLabel.Text = "Upload status: File uploaded!";
Newfilename = fileLocation;
Defaultfilename = Path.GetFileName(ASPxUploadControl1.FileName);
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
else
{
StatusLabel.Text = "Please choose excel file";
}
}
}
Path.GetExtension returns null if the passed value is null and returns string.Empty if the passed value doesn't have an extension.
So please check if the value inside ASPxUploadControl1.FileName actually contains something usefull.
If this is not the case then you'll have to look up where the value is set and debug from there to find out why it's not set.
Can you step through the execution?
Does
NewFilename = fileLocation;
get executed?
If so, what are the values for NewFilename before and after?
This looks like ASP.Net code.
If it is. Is the problem that when you try to use NewFilename elsewhere in the code-behind is is blank.
If you are, then NewFilename may need to be saved to the session to allow you to use it.
hth,
Alan.