I want to show file upload progress in c# application - c#

I want to show a file upload progress in c# windows application As I am using online database it takes a bit more time to save or upload.I am using following Code.I have searched but It does not shows exact percent wise progress.Also I Want to change file name before moving to another lOcation.
Thanks In advance.
OpenFileDialog dlg = new OpenFileDialog();
DialogResult dlgRes = dlg.ShowDialog();
Application.DoEvents();
label14.Visible = true;
if (DialogResult.OK != DialogResult.Cancel)
{
foreach (string file in dlg.FileNames)
{
try
{
newpath = Path.Combine(textBox2.Text, Path.GetFileName(file)).ToString();
filenametemp = "tush" + Path.GetFileName(file).ToString();
if (String.IsNullOrEmpty(textBox2.Text))
{
MessageBox.Show("please select folder to save");
}
else
{
File.Copy(file, Path.Combine(textBox2.Text, Path.GetFileName(file)).ToString());
if (dlgRes != DialogResult.Cancel)
{
//Provide file path in txtFilePath text box.
txtFilePath.Text = dlg.FileName;
}
//string folderpath = System.IO.Directory.GetParent(Environment.CurrentDirectory).Parent.FullName + textBox2.Text;
//string filePath = textBox2.Text + System.IO.Path.GetFileName(dlg.FileName);
//System.IO.File.Copy(dlg.FileName, folderpath, true);
try
{
//Read File Bytes into a byte array
byte[] FileData = ReadFile(txtFilePath.Text);
//Initialize SQL Server Connection
SqlConnection CN = new SqlConnection(ConfigurationManager.ConnectionStrings["Copymanagment"].ConnectionString);
//Set insert query
string qry = "insert into fileinfo (File_Id,File_Path,date,OriginalPath,Billnumber,Billdate,FileData) values(#FileId,#Filepath,#Date,#OriginalPath,#Billnumber,#Billdate,#FileData)";
//Initialize SqlCommand object for insert.
SqlCommand SqlCom = new SqlCommand(qry, CN);
string path = textBox2.Text;
string[] arrpath = null;
int count;
arrpath = path.Split('\\');
for (count = 0; count <= arrpath.Length - 1; count++)
{
// MessageBox.Show(arrpath[count]);
}
string folder = arrpath[arrpath.Length - 1] + databaseid().ToString();
//We are passing Original File Path and File byte data as sql parameters.
string fileid = Path.GetDirectoryName(dlg.FileName);
SqlCom.Parameters.Add(new SqlParameter("#FileId", (object)folder));
SqlCom.Parameters.Add(new SqlParameter("#Filepath", (object)newpath));
SqlCom.Parameters.Add(new SqlParameter("#Date", (object)System.DateTime.Now.ToString("dd-MM-yyyy hh:mm:ss tt")));
SqlCom.Parameters.Add(new SqlParameter("#OriginalPath", (object)txtFilePath.Text));
SqlCom.Parameters.Add(new SqlParameter("#Billnumber", (object)textbillno.Text));
SqlCom.Parameters.Add(new SqlParameter("#Billdate", (object)dateTimePicker1.Value.ToString("dd-MM-yyyy")));
SqlCom.Parameters.Add(new SqlParameter("#FileData", (object)FileData));
//Open connection and execute insert query.
CN.Open();
SqlCom.ExecuteNonQuery();
CN.Close();
label14.Visible = false;
//Close form and return to list or Files.
MessageBox.Show("File saved Succsesfully");
txtFilePath.Text = "";
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
catch
{
MessageBox.Show("File already available");
}
}
}

The way you have it done, a single statement in inserting the whole data in one shot and blocks until done without a chance to update tge UI. You can upload your BLOB data in chuncks using UPDATETEXT. see https://msdn.microsoft.com/en-us/library/vstudio/3517w44b(v=vs.100).aspx for full explanations on how to do that. Doing that, you will have the opportunity to update the value of a prigress bar.

You can use asp.net ajax control toolkit. There is a ajax file upload control.
Note Do not get confused with asynFile upload control in the same library(that control does not have progress bar).
You can get info here http://www.codingfusion.com/Post/AjaxFileUpload-example-to-upload-multiple-files-in
To download the library go here http://www.codingfusion.com/Post/3-Different-ways-to-add-AjaxControlToolkit-in-Asp
for windows app try following https://stackoverflow.com/a/9446524/4810628

Related

How to search image which image name contain '12345' in textbox

I'm a newbie in C# programming language. I need some guide on how can I search image in textbox which just typing image name that contain 12345. This is because each image name in my folder is naming like this > JUN (12345). I want the image display at picturebox after typing 12345 in textbox. Here is my code that I already try it not display image that contain 12345. Hope anyone can help me. Thanks
private void textBoxWorkNo_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (textBoxWorkNo.Text != "")
{
//Do something
string selectSql = "select name, empno, icnum, passport, deptno, section, designation from m_employee where workno=#workno";
SqlCommand cmd = new SqlCommand(selectSql, con);
cmd.Parameters.AddWithValue("#workno", textBoxWorkNo.Text);
bool isDataFound = false;
try
{
con.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
while (read.Read())
{
isDataFound = true;
textBoxEmplNo.Text = (read["empno"].ToString());
textBoxName.Text = (read["name"].ToString());
textBoxICPass.Text = (read["icnum"].ToString());
textBoxPassport.Text = (read["passport"].ToString());
textBoxDept.Text = (read["deptno"].ToString());
textBoxSection.Text = (read["section"].ToString());
textBoxDesignation.Text = (read["designation"].ToString());
//BaseFolder that contains the multiple folders
//If the folders don't share the same base folder make an array with full paths
string baseFolder = "C:\\Users\\hamizah\\Desktop\\photo";
string[] employeeFolders = Directory.GetDirectories(baseFolder);
//Search image
string imgName = "%'" + textBoxEmplNo.Text + "%'" + ".jpg";
//Bool to see if file is found after checking all
bool fileFound = false;
foreach (var folderName in employeeFolders)
{
var path = Path.Combine(folderName, imgName);
if (File.Exists(path))
{
pictureBox1.Visible = true;
pictureBox1.Image = Image.FromFile(path);
fileFound = true;
//If you want to stop looking, break; here
}
}
if (!fileFound)
{
//Display message that No such image found
pictureBox1.Visible = true;
pictureBox1.Image =
Image.FromFile(#"C:\Users\hamizah\Desktop\images\photo\No-image-found.jpg");
}
dataGridView1.Visible = false;
}
}
if (!isDataFound)
{
textBoxEmplNo.Text = "";
textBoxWorkNo.Text = "";
textBoxName.Text = "";
// Display message here that no values found
MessageBox.Show("No Result Found");
}
}
finally
{
con.Close();
}
}
else
{
textBoxEmplNo.Text = "";
textBoxName.Text = "";
}
}
}
File.Exists looks for one specific file. There is no file with weird name %'12345%'.jpg I guess. You can use this form:
foreach (var f in Directory.EnumerateFiles(rootPath, "*12345*.jpg")){
...
}
If it's already on the disk just use Directory.GetFiles() like so:
var strings = Directory.GetFiles(".","*12345*");
foreach (var s in strings)
{
Debug.Write(s);
}
You can use below code to get the files in the specific directory, which has a partial matching names as input value.
For each directory you are iterating through get the directory info first:
DirectoryInfo directoryInfo = new DirectoryInfo(#"c:\");
Then get the files as mentioned below:
FileInfo[] fileInfoArray = directoryInfo.GetFiles("*" + inputFileName + "*.*");
Then you can check the fileInfoArray for the file you are looking for. It can return multiple file info, depending on your input.
For reference: added the actual code here:
string partialInputName = "12345"; //textbox input value or whatever you want to input
string[] directories = Directory.GetDirectories(#"C:\Code");
FileInfo fileinDir;
foreach(string dir in directories)
{
DirectoryInfo dirInfo = new DirectoryInfo(dir);
if (dirInfo.Exists)
{
//taking the first (FirstOrDefault()), considering that all files have a unique name with respect to the input value that you are giving. so it should fetch only one file every time you query
fileinDir = dirInfo.GetFiles("*" + partialInputName + "*.*").FirstOrDefault();
}
}

Download multiple files in same record from a database table

I have this table to store Purchase Order data, it can hold up to 3 files (first file is required, second and third is optional) which their column names are highlighted in the picture.
I have already done the Upload page, which save all the data entered and uploaded by user to the database, it is working fine, I can see all the saved file names and bytes in the table.
I am working on the View page, which retrieve data from database and display it to the webpage and have problem of retrieving the files.
The idea is to display the file name to the page (which is working fine) and when user click onto the file name, they can save it to the computer (or open/run etc depend on web browser prompt windows), problem here is that: I can only save the first file, when clicking on the second and third file name, nothing happened although when in debugging mode they (name, type and data of file2 and file3) do exist but the prompt windows to save file is not appeared
Any idea how to fix this or if anyone have better method of how to download these files please help.
Here is my code (please ignore the unrelated codes or please let me know if you want to know what they do):
The View.aspx to display file names
<asp:LinkButton ID="lbtPOFile" runat="server" OnClick="lbtPOFile_Click"></asp:LinkButton>
<asp:LinkButton ID="lbtPOFile2" runat="server" OnClick="lbtPOFile2_Click"></asp:LinkButton>
<asp:LinkButton ID="lbtPOFile3" runat="server" OnClick="lbtPOFile3_Click"></asp:LinkButton>
C# behind: the DownloadFile() method has 3 parameters, they are just column names in the database table, corresponding to the file1, file2 or file3, it supposes to retrieve the file when user click onto the file name (called in the click events below)
protected void DownloadFile(string fileNameColumn, string fileTypeColumn, string fileDataColumn)
{
string guid = !string.IsNullOrEmpty(Request.QueryString["guid"]) ? Request.QueryString["guid"] : Guid.Empty.ToString();
string id = !string.IsNullOrEmpty(Request.QueryString["id"]) ? Request.QueryString["id"] : "0";
if (requestDAL.ValidatePODetailLink(guid, Convert.ToInt32(id)))
{
byte[] bytes = null;
string fileName = "";
string contentType = "";
DataTable PODetail = requestDAL.GetPODetail(guid, Convert.ToInt32(id));
foreach (DataRow row in PODetail.Rows)
{
bytes = (byte[])row[fileDataColumn];
contentType = row[fileTypeColumn].ToString();
fileName = row[fileNameColumn].ToString();
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = contentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
else
{
//Display message
InfoPanel.Visible = true;
lblMessage.Text = "<b>Invalid file or an error has occurred while connecting to the database. Please try again later!</b>";
lblMessage.CssClass = "text text-danger bold";
InfoPanel.CssClass = "panel panel-danger";
FormPanel.Visible = false;
FormPanel.Enabled = false;
}
}
protected void lbtPOFile_Click(object sender, EventArgs e)
{
try
{
DownloadFile("poFileName", "poFileContentType", "poFileData");
}
catch (Exception ex)
{
//Display message
InfoPanel.Visible = true;
lblMessage.Text = "<b>An error has occurred. Please try again later!</b></br>" + ex.Message;
lblMessage.CssClass = "text text-danger bold";
InfoPanel.CssClass = "panel panel-danger";
FormPanel.Visible = false;
FormPanel.Enabled = false;
}
}
protected void lbtPOFile2_Click(object sender, EventArgs e)
{
try
{
DownloadFile("poFileName2", "poFileContentType2", "poFileData2");
}
catch (Exception ex)
{
//Display message
InfoPanel.Visible = true;
lblMessage.Text = "<b>An error has occurred. Please try again later!</b></br>" + ex.Message;
lblMessage.CssClass = "text text-danger bold";
InfoPanel.CssClass = "panel panel-danger";
FormPanel.Visible = false;
FormPanel.Enabled = false;
}
}
protected void lbtPOFile3_Click(object sender, EventArgs e)
{
try
{
DownloadFile("poFileName3", "poFileContentType3", "poFileData3");
}
catch (Exception ex)
{
//Display message
InfoPanel.Visible = true;
lblMessage.Text = "<b>An error has occurred. Please try again later!</b></br>" + ex.Message;
lblMessage.CssClass = "text text-danger bold";
InfoPanel.CssClass = "panel panel-danger";
FormPanel.Visible = false;
FormPanel.Enabled = false;
}
}
Some related functions in case you need it:
// Validate link for employee (link format is View.aspx?guid=xxx&id=xxx)
public static bool ValidatePODetailLink(string guid, int poID)
{
using (SqlConnection con = new SqlConnection(CS))
{
string query = "SELECT COUNT(*) FROM PO WHERE poID = #poID AND poGUID = #guid";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#guid", guid);
cmd.Parameters.AddWithValue("#poID", poID);
con.Open();
int i = Convert.ToInt32(cmd.ExecuteScalar());
if (i == 1) return true;
else return false;
}
}
//Get po request details for employee
public static DataTable GetPODetail(string guid, int poID)
{
using (SqlConnection con = new SqlConnection(CS))
{
string query = "SELECT * FROM PO WHERE poID = #poID AND poGUID = #guid";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#guid", guid);
cmd.Parameters.AddWithValue("#poID", poID);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
PROBLEM FOUND:
I use UpdatePanel and only put <Triggers> <asp:PostBackTrigger ControlID="lbtPOFile" /> </Triggers> hence it was missing PostBackTrigger for lbtPOFile2 and lbtPOFile3. Added those 2 lines and it works.
I would suggest the following approach.
Revert your code to the "known good" state (where it can only handle the download of one file, but does so correctly)
Refactor this code so that it still supports a single file download. Take the code that streams the file contents into the response; move it into a separate function (perhaps call this SendFile); call that function from your click handler; recompile and confirm that everything is still working.
Now modify SendFile so that it accepts input parameters that determine whether it will return file 1, file 2, or file 3. Modify the click handler so that it passes the parameters that indicate file 1. Recompile and test again, make sure it still works.
Now add two additional click handlers for your other two link buttons. Should be identical to your existing click handler except for the arguments that are passed to SendFile. Recompile and test with all three files.

How to store video files in SQL database using asp.net? [duplicate]

I have scenario where i want to store video into database and show in grid to download from database ,i will upload video by fileupload control and it should be sql server2008 database,which is best way in c# and asp.net?
There are many link for it. Check out this.
http://weblogs.asp.net/hajan/archive/2010/06/21/save-and-display-youtube-video-links-on-asp-net-website.aspx
http://forums.asp.net/t/1104451.aspx/1?How+to+retrieve+video+file+from+sql+server+database
http://www.saurabhdeveloper.com/techtips_details.php?tipsid=15
http://forums.asp.net/p/1533758/3719583.aspx
http://forums.asp.net/t/1045855.aspx/2/10
http://forums.asp.net/t/1511588.aspx/1
http://www.dotnetspider.com/forum/274821-Play-video-file-asp-net-page.aspx
http://blogs.ugidotnet.org/kfra/archive/2006/10/04/50003.aspx
http://www.dotnetspider.com/resources/16239-code-for-video-upload.aspx
http://www.c-sharpcorner.com/Forums/Thread/88899/
http://www.asp.net/webmatrix/tutorials/10-working-with-video
http://www.c-sharpcorner.com/Forums/Thread/88899/
Try this code
byte[] buffer;
//this is the array of bytes which will hold the data (file)
SqlConnection connection;
protected void ButtonUpload_Click(object sender, EventArgs e)
{
//check the file
if (FileUpload1.HasFile && FileUpload1.PostedFile != null
&& FileUpload1.PostedFile.FileName != "")
{
HttpPostedFile file = FileUpload1.PostedFile;
//retrieve the HttpPostedFile object
buffer = new byte[file.ContentLength];
int bytesReaded = file.InputStream.Read(buffer, 0,
FileUpload1.PostedFile.ContentLength);
if (bytesReaded > 0)
{
try
{
string connectionString =
ConfigurationManager.ConnectionStrings[
"uploadConnectionString"].ConnectionString;
connection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand
("INSERT INTO Videos (Video, Video_Name, Video_Size)" +
" VALUES (#video, #videoName, #videoSize)", connection);
cmd.Parameters.Add("#video",
SqlDbType.VarBinary, buffer.Length).Value = buffer;
cmd.Parameters.Add("#videoName",
SqlDbType.NVarChar).Value = FileUpload1.FileName;
cmd.Parameters.Add("#videoSize",
SqlDbType.BigInt).Value = file.ContentLength;
using (connection)
{
connection.Open();
int i = cmd.ExecuteNonQuery();
Label1.Text = "uploaded, " + i.ToString() + " rows affected";
}
}
catch (Exception ex)
{
Label1.Text = ex.Message.ToString();
}
}
}
else
{
Label1.Text = "Choose a valid video file";
}
}
You say it "should" be SQL Server 2008, but does it have to be?
If not, SQL Server 2012 offers File Tables that are designed for storing large files in SQL Server. It actually stores the data on the filesystem but in a way that you don't have to write any code to manage the actual file.
If it does need to be SQL Server 2008 then you have the following options:
1) FileStream using a varbinary(MAX) column type - there can be performance issues with this method. I personally would not store video in this way.
2) Put the file on the file system (on disk) and only store the filepath/filename in the DB. You then write code to manage CRUD operations on the file system.
It will help you... see the following link http://www.codeproject.com/Articles/308552/Upload-and-Download-Files-to-SQL-Servers-in-ASP-Ne

sqlBulk insert C#

I have a page where I want to upload a CSV file from my computer to database on the server and I have my opentext that looks like the following
using (StreamReader sr = File.OpenText(#"c:\users\workstationUsername\FileName.csv"))
This works fine on my local machine but when I push this to the server it tries to read the server's C Drive and I want it to read the physical file location that is sitting on the desktop of the user's computer not the server, when they click browse and upload..
Thank you
below is the complete code:
if (IsPostBack)
{
// SetDefaultDates();
Boolean fileOK = false;
String dateString = DateTime.Now.ToString("MMddyyyy");
String UserName = User.Identity.Name;
String path = Server.MapPath("~/Uploads/CSVs/");
string stringpath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
String fileName = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
stringpath = stringpath + fileName;
String LocationToSave = path + "\\" + fileName;
if (FileUpload1.HasFile)
{
String fileExtension =
System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
String[] allowedExtensions = { ".csv" };
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])
{
fileOK = true;
}
}
}
if (fileOK)
{
try
{
//FileUpload1.PostedFile.SaveAs(LocationToSave + dateString + "-" + FileUpload1.FileName);
FileUpload1.PostedFile.SaveAs(LocationToSave);
Label1.Text = "File " + FileUpload1.FileName + " uploaded!";
DataTable dt = new DataTable();
string line = null;
int i = 0;
using (StreamReader sr = File.OpenText(stringpath))
{
while ((line = sr.ReadLine()) != null)
{
string[] data = line.Split(',');
if (data.Length > 0)
{
if (i == 0)
{
foreach (var item in data)
{
dt.Columns.Add(new DataColumn());
}
i++;
}
DataRow row = dt.NewRow();
row.ItemArray = data;
dt.Rows.Add(row);
}
}
}
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["Myconnection"].ConnectionString))
{
cn.Open();
using (SqlBulkCopy copy = new SqlBulkCopy(cn))
{
copy.WriteToServer(dt);
}
}
}
catch (Exception ex)
{
Label1.Text = "File " + FileUpload1.FileName + " could not be uploaded." + ex.Message;
}
}
else
{
Label1.Text = "Cannot accept files of this type. " + FileUpload1.FileName;
}
}
SetDefaultDates();
}
If you have a FileUpload control, then instead of using (StreamReader sr = File.OpenText(#"c:\users\workstationUsername\FileName.csv")) which obvously is pointing to the server's hard drive you can do this:
(StreamReader sr = new StreamReader(fileUploadControl.FileContent))
//Do your stuff
You can't access the client's hard drive. That's a major security concern. You'll need to upload the file to your server, and read it from there.
It doesnt make sense to have a static read to the local machine, rather get user to upload it then update the database, this code is very limiting and has a high security risk. Rather create a steamreader object get the user to upload it then use the steam reader to process the csv.

reading Html file through OLEDB fails

i am trying to read html file through OLEDB reader using following code
DataTable dTable;
string strDataSource = "";
string strDBFile = "";
long intPos = 0;
strDataSource = mstrFilePath;
dTable = new DataTable();
mCon = new System.Data.OleDb.OleDbConnection();
mCon.ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + openFileDialog1.FileName + ";Extended Properties=\"HTML Import;HDR=NO;IMEX=1\";");
if (mCon.State == ConnectionState.Closed)
{
mCon.Open(); // gettting failed here
}
dTable = mCon.GetSchema("Tables");
bSelectionChanged = true;
lstTables.Items.Clear();
foreach (DataRow DRow in dTable.Rows)
{
if (DRow["TABLE_TYPE"].ToString() == "TABLE" || DRow["TABLE_TYPE"].ToString() == "VIEW")
{
intPos = DRow["TABLE_NAME"].ToString().LastIndexOf("FilterDatabase");
lstTables.Items.Add(DRow["TABLE_NAME"]);
}
}
if (lstTables.Items.Count == 1)
{
lstTables.Visible = false;
grdSampleDataControl.Dock = DockStyle.Fill;
}
else
{
lstTables.Visible = true;
grdSampleDataControl.Dock = DockStyle.None;
}
bSelectionChanged = true;
dTable.Dispose();
mCon.Close();
openFileDialog1.Dispose();
It is getting failed here wiht exception\
The Microsoft Office Access database engine cannot open or write to the file ''. It is already opened exclusively by another user, or you need permission to view and write its data.
But file is not opened anywhere ??
Edit
On debug, When it throws exception at mCon.Open(), If i press F10 compiler moves to next statement and run the programm succesfully. why it is so ??
This is happening because your Acccess Database file is open.
You can not keep file open, and do changes on that file dynamically.
While the program using that file is running, it tries to open that file.
But, if file is already open exclusively by user, then it fails.
Close the file, and then try to open the connection.
For other details on it, follow this DISCUSSION.

Categories

Resources