how to check file format - c#

the allowed file format is only PDF file, how to check the file format and display error message if the uploaded file is not PDF before proceeding to update database. The following code always displays the file is not recognized even the file is PDF and also the database not updated.
string filePath = FileUpload1.PostedFile.FileName;
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);
string contenttype = String.Empty;
switch (ext)
{
case ".pdf":
contenttype = "application/pdf";
break;
default:
System.Console.WriteLine("File format not recognised. Only PDF format allowed");
break;
}
if (contenttype != String.Empty)
{
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
string classNmae = ddClass.Text.Split('~')[0] + ddClass.Text.Split('1');
com.Parameters.Clear();
com.CommandText = "UPDATE [Marking] SET [fileName]=#fileName, [fileType]=#fileType, [type]=#typ,[submissionDate]=#sd, [filePath]=#fp where [class_id]=#cid AND [module_id]=#mid AND [student_id]= '" +Session["id"].ToString() + "'";
com.Parameters.Add("#cid", SqlDbType.VarChar).Value = ddClass.Text.Split('~')[0];
com.Parameters.Add("#mid", SqlDbType.VarChar).Value = ddClass.Text.Split('~')[1];
com.Parameters.Add("#fileName", SqlDbType.VarChar).Value = filename;
com.Parameters.Add("#fileType", SqlDbType.VarChar).Value = "application/pdf";
com.Parameters.Add("#typ", SqlDbType.VarChar).Value = txtType.Text;
com.Parameters.Add("#sd", SqlDbType.VarChar).Value = DateTime.Now;
com.Parameters.Add("#fp", SqlDbType.Binary).Value = bytes;
com.ExecuteNonQuery();
}
else
{
lb.Text = "File format not recognised." +
" Upload Word formats";
}

Try this:
if (FileUpload1.HasFile)
{
HttpPostedFile myPostedFile = FileUpload1.PostedFile;
FileInfo finfo = new FileInfo(myPostedFile.FileName);
if (finfo.Extension.Equals(".pdf", StringComparison.InvariantCultureIgnoreCase) && IsPdf(finfo.FullName))
{
//do the operation
}
}
public bool IsPdf(string sourceFilePath)
{
var bytes = System.IO.File.ReadAllBytes(sourceFilePath);
var match = System.Text.Encoding.UTF8.GetBytes("%PDF-");
return match.SequenceEqual(bytes.Take(match.Length));
}
Updated as per #Darek's and #Andrew's suggestion.

Here is one way to find out if at least the file has a PDF header:
var bytes = File.ReadAllBytes(someFileNameHere);
var match = Encoding.UTF8.GetBytes("%PDF-");
var isPDF = match.SequenceEqual(bytes.Take(match.Length));

Related

Convert from a DataUrl to an Image in C# and write a file with the bytes

Hello I have signature like this:
which is encoded to a DataUrl specifically this string:
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAADICAYAAADGFbfiAAAYlElEQVR4Xu2dC8w1R1nHQSCIgIKVGLmoiLciFwUs... (long string)"
What i want to do is Convert this DataUrl to an PNG Image, and save the image to the device, this is what i am doing so far:
if (newItem.FieldType == FormFieldType.Signature)
{
if (newItem.ItemValue != null)
{
//string completeImageName = Auth.host + "/" + li[i];
string path;
string filename;
string stringName = newItem.ItemValue;
var base64Data = Regex.Match(stringName, #"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
var binData = Convert.FromBase64String(base64Data);
path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
filename = Path.Combine(path, base64Data);
if (!File.Exists(filename))
{
using (var stream = new MemoryStream(binData))
{
//Code crashing here--------------------------
File.WriteAllBytes(filename, binData);
}
}
newItem.ItemValue = filename;
}
}
App.Database.SaveReportItem(newItem);
But my code is making my application to crash specifically in this line:
File.WriteAllBytes(filename, binData);
The sample I am using as reference (Link) is using a PictureBox but with Xamarin there is no use of a pictureBox.
Any Ideas?
As #SLaks mentioned I didn't need a MemoryStream, the problem with my code was the path and the filename for further help this is the working code:
if (newItem.FieldType == FormFieldType.Signature)
{
if (newItem.ItemValue != null)
{
//string completeImageName = Auth.host + "/" + li[i];
string path;
string filename;
string stringName = newItem.ItemValue;
var base64Data = Regex.Match(stringName, #"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
var binData = Convert.FromBase64String(base64Data);
path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
//filename = Path.Combine(path, base64Data.Replace(#"/", string.Empty));
long milliseconds = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
string fileName = "Sn" + milliseconds.ToString() + ".PNG";
filename = Path.Combine(path, fileName);
if (!File.Exists(filename))
{
//using (var stream = new MemoryStream(binData))
//{
File.WriteAllBytes(filename, binData);
//}
}
newItem.ItemValue = filename;
}
}
App.Database.SaveReportItem(newItem);
And the image showed:
I just cleaned Mario's code and fine tuned regex:
public string SaveDataUrlToFile(string dataUrl, string savePath)
{
var matchGroups = Regex.Match(dataUrl, #"^data:((?<type>[\w\/]+))?;base64,(?<data>.+)$").Groups;
var base64Data = matchGroups["data"].Value;
var binData = Convert.FromBase64String(base64Data);
System.IO.File.WriteAllBytes(savePath, binData);
return savePath;
}

Read credentials in text file for program c#?

This is my program, and it work correctly if i put username and password :
try
{
var url = #"https://mail.google.com/mail/feed/atom";
var User = username;
var Pasw = password;
var encoded = TextToBase64(User + ":" + Pasw);
var myweb = HttpWebRequest.Create(url) as HttpWebRequest;
myweb.Method = "POST";
myweb.ContentLength = 0;
myweb.Headers.Add("Authorization", "Basic " + encoded);
var response = myweb.GetResponse();
var stream = response.GetResponseStream();
textBox1.Text += ("Connection established with" + User + Pasw);
}
catch (Exception ex)
{
textBox1.Text += ("Error connection. Original error: " + ex.Message);
now i want read string of texfile, split them and read username and password like this format: username:password . There is my code at the moment:
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
string file_name = "";
file_name = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + file_name;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (StringReader reader = new StringReader(file_name))
{
// Loop over the lines in the string.
int count = 0;
string line;
while ((line = reader.ReadLine()) != null)
{
string[] data = line.Split(':');
string username = data[0].Trim();
string password = data[1].Trim();
count++;
/* Console.WriteLine("Line {0}: {1}", count, line); */
}
reader.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
You open the file selected by the user, but then try to read from a variable file_name that is not the name of a file but the name of a well kwown folder. Perhaps you want this
try
{
if (openFileDialog1.FileName != string.Empty)
{
using (StreamReader reader = new StreamReader(openFileDialog1.FileName))
{
....
}
}
}
In this same code you use a StringReader, but instead you need a StreamReader to read from a file. StringReader takes the value passed in its constructor and return in the ReadLine call. Then you split the line at the colon but of course this is not the content of your file.
There are other problems in your code. For example, what do you do with the username and password loaded from the line? They are declared as local variables and not used anywhere, so at the next loop they are overwritten and lost.
So, a UserData class could be a possible answer
public class UserData
{
public string UserName {get; set;}
public string Password {get; set;}
}
and declare at the form global level an
List<UserData> data = new List<UserData>
and in your loop
public void button1_Click(object sender, EventArgs e)
{
try
{
if (openFileDialog1.FileName != string.Empty)
{
using (StreamReader reader = new StreamReader(openFileDialog1.FileName))
{
int count = 0;
string line;
while ((line = reader.ReadLine()) != null)
{
UserData d = new UserData();
string[] parts = line.Split(':');
d.UserName = parts[0].Trim();
d.Password = parts[1].Trim();
data.Add(d);
}
// At the loop end you could use the List<UserData> like a normal array
foreach(UserData ud in data)
{
Console.WriteLine("User=" + dd.UserName + " with password=" + dd.Password);
}
}
}
}
}
public void button2_Click(object sender, EventArgs e)
{
try
{
if(data.Count() == 0)
{
MessageBox.Show("Load user info first");
return;
}
var url = #"https://mail.google.com/mail/feed/atom";
var encoded = TextToBase64(data[0].UserName + ":" + data[0].Password);
.....
A warning note. Of course this is just demo code. Remember that in a real scenario saving passwords in clear text is a big security concern. The impact of this is relative to the context of your application but should not be downplayed. A better course of action is to store an hashing of the password values and apply the same hashing function when you need to compare password
You are creating StringReader from file_name varialbe, which is (according to your code)
string file_name = "";
file_name = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + file_name;
and points to nothere.
Also you have stream created for file being selected with open file dialog but you haven't use this stream.

Pdf file is not updating in asp.net application

In my asp.net application we generating pdf using ITextSharp.dll
Now my problem is every time same pdf is opening(not refreshing) unless until clear my browser history it is same. I am using chrome browser.
Here is my code
private void fillForm() {
try {
string Phone = "", Physical = "";
string formFile = Server.MapPath("~\\Inspection.pdf");
string newFile = Server.MapPath("~\\InspectionPrint.pdf");
PdfReader reader = new PdfReader(formFile);
PdfStamper stamper = new PdfStamper(reader, new FileStream(newFile, FileMode.Create));
AcroFields fields = stamper.AcroFields;
PdfContentByte d = new PdfContentByte(stamper.Writer);
//getting values from DB
SqlCommand comd = new SqlCommand("usp_PrintInspection", QMSConn);
QMSConn.Open();
comd.CommandType = CommandType.StoredProcedure;
comd.Parameters.Add("#QuoteNumber", SqlDbType.VarChar);
comd.Parameters["#QuoteNumber"].Value = Session["CurrQuoteNumber"].ToString();
DataSet ds = new DataSet();
SqlDataAdapter sqlAdapter = new SqlDataAdapter();
sqlAdapter.SelectCommand = comd;
sqlAdapter.Fill(ds, "Table");
if (ds.Tables[0].Rows.Count > 0) {
// set form fields
string Name = ds.Tables[0].Rows[0]["NAME"].ToString();
string Address1 = ds.Tables[0].Rows[0]["Address1"].ToString();
string CompanyID = ds.Tables[0].Rows[0]["CompanyID"].ToString();
string PolicyNumber = ds.Tables[0].Rows[0]["PolicyNumber"].ToString();
fields.SetField("Name", Name);
fields.SetField("Address1", Address1);
fields.SetField("CompanyID ", CompanyID);
fields.SetField("PolicyNumber", PolicyNumber);
stamper.FormFlattening = false;
stamper.Close();
string file = "InspectionPrint";
string Url = "../" + file + ".pdf";
String js = #"WindowPopup('" + Url + "');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "Key", js, true);
}
else {
showalert("No Record Available For This Quote");
}
}
catch(exception ex) {
}
}
as you are saying it is working in the Localhost but not in the production server, most likely it seems to me as an URL/Path issue.
1. after observing your code, you are creating one more string Url variable without using the existing String formFile variable.
as you should provide the valid path you need to use the formFile instead of Url as you have created formFile using Server.MapPath()
Try This:
/*string Url = "../" + file + ".pdf";*/ //comment or remove
String js = #"WindowPopup('" + formFile + "');";//use formFile instead of Url

How to restrict the other format files from Displaying while browsing with File Upload for Selecting a File to Upload?

In my Project I am Uploading Doc or PDF file for the Reference of the User during the "File Upload" browse all the files including Doc and PDF files are displaying to select so I used IF condition in my Code to check whther the file selected was DOC or PDF but I want only DOC and PDF files to be displayed for selection to discard the IF statement my Code is,
if (FileUpload1.HasFile != false)
{
// Read the file and convert it to Byte Array
string filePath = FileUpload1.PostedFile.FileName;
int size = FileUpload1.PostedFile.ContentLength;
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);
string contenttype = String.Empty;
int bufferSize = 1;
byte[] buffer = new byte[bufferSize];
//Set the contenttype based on File Extension
switch (ext)
{
case ".doc":
contenttype = "application/vnd.ms-word";
break;
case ".docx":
contenttype = "application/vnd.ms-word";
break;
case ".pdf":
contenttype = "application/pdf";
break;
}
if (size <= 5242880)
{
if (contenttype != String.Empty && ext == ".doc" || ext == ".docx" || ext == ".pdf")
{
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
string fname = #"E:\Rajesh_Kumar\Application\Valuation\ExamManagement\ExamManagement\FileUpload";
Directory.CreateDirectory(fname);
string strFullFilename = #"E:\Rajesh_Kumar\Application\Valuation\ExamManagement\ExamManagement\FileUpload\" + FileUpload1.FileName;
//SqlCommand qry = new SqlCommand("select Filepath from answerkey");
FileInfo file = new FileInfo(strFullFilename);
//FileInfo file1 = new FileInfo(qry);
fname = Path.Combine(fname, strFullFilename);
if(file.Exists)
{
lblMessage.Visible = true;
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "File - ''"+filename+"'' - already Exists in the Database !!!";
FileUpload1.Focus();
}
else
{
//insert the file into database
string strQuery = "insert into answerkey(Filename, Type, Data,Filepath)" + " values (#Filename, #Type, #Data,#Filepath)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#Filename", SqlDbType.VarChar).Value = filename;
cmd.Parameters.Add("#Type", SqlDbType.VarChar).Value = contenttype;
cmd.Parameters.Add("#Data", SqlDbType.Binary).Value = bytes;
cmd.Parameters.Add("#Filepath", SqlDbType.VarChar).Value = filePath;
InsertUpdateData(cmd);
File.Copy(filePath, strFullFilename, true);
lblMessage.Visible = true;
lblMessage.ForeColor = System.Drawing.Color.Green;
string filename1 = Path.GetFileNameWithoutExtension(filename);
lblMessage.Text = "File - '' " + filename1 + " '' - of Size - ''" + size + " bytes'' - has been Uploaded Successfully";
}
}
else
{
lblMessage.Visible = true;
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "File format not recognised.Upload Word/PDF formats Only";
FileUpload1.Focus();
}
}
else
{
lblMessage.Visible = true;
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "File Size is larger than 5 MB !!!";
FileUpload1.Focus();
}
}
else
{
lblMessage.Visible = true;
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "Please Select a File !!!";
FileUpload1.Focus();
}
}
Thanks in Advance...
In case of web, you cannot do that.
For a way around, you can see the link:
How to restrict file type in FileUpload control
Use Regular Expression Validator:
<asp:RegularExpressionValidator
id="RegularExpressionValidator1" runat="server"
ErrorMessage="Only Word and PDF files are allowed!"
ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.pdf|.PDF|.doc|.DOC|.docx|.DOCX)$"
ControlToValidate="FileUpload1" CssClass="text-red"></asp:RegularExpressionValidator>
Hope this will help :)

Uploading a text file in ASP.NET

I have a web page on which users can upload text files (but a text file, i.e. a file with the extension .txt, could be of many encodings, e.g. ASCII, UTF8, UNICODE .. etc), I'm trying to validate the contents in memory before I save the file to the disk, if the content is not valid, I don't save the file. I'm reading the content from the file upload control (fileUpload1.FileContent which returns a stream of bytes), is there an easy way in .NET to convert the content of the uploaded file to a string (i.e. the byte stream returned from fileUpload1.FileContent) or will I have to check the first bytes to detect the encoding first?
Thanks
I think you can do this:
StreamReader reader = new StreamReader(fileUpload1.FileContent);
string text = reader.ReadToEnd();
Example of text file format
Code#Name#Fathername#DOB#Location#MobileNo
1#XYZ#YYY#09-06-89#LKO#9999999999
protected void btnUpload_click(object sender, EventArgs e)
{
if (Page.IsValid)
{
bool logval = true;
if (logval == true)
{
if (fuUploadExcelName.HasFile)
{
String img_1 = fuUploadExcelName.PostedFile.FileName;
String img_2 = System.IO.Path.GetFileName(img_1);
string extn = System.IO.Path.GetExtension(img_1);
string frstfilenamepart = "Text" + DateTime.Now.ToString("ddMMyyyyhhmmss");/*Filename for storing in Desired path*/
UploadExcelName.Value = frstfilenamepart + extn;
fuUploadExcelName.SaveAs(Server.MapPath("~/Text/") + "/" + UploadExcelName.Value);/*Uploaded text file will be store at this path*/
string filename = UploadExcelName.Value;
string filePath = Server.MapPath("~/Text/" + filename);
StreamReader file = new StreamReader(filePath);
string[] ColumnNames = file.ReadLine().Split('#');/*read data from textfile*/
DataTable dt = new DataTable();
foreach (string Column in ColumnNames)
{
dt.Columns.Add(Column);/*adding the columns/
}
string NewLine;
while ((NewLine = file.ReadLine()) != null)
{
DataRow dr = dt.NewRow();
string[] values = NewLine.Split('#');
for (int i = 0; i < values.Length; i++)
{
dr[i] = values[i].TrimEnd();
}
dt.Rows.Add(dr);
}
file.Close();
grdview.DataSource = dt;/*make datasouce from text file*
grdview.DataBind();/*binding the grid*/
}
}
}
}

Categories