Error reading words in the text file - asp.net

I have been working on a code snippet today . A part of the Code reads the number of words in the file.I am using StreamReader to do the same , but it seems to give DirectoryNotFound Exception.Here is the code for the event
protected void Button1_Click(object sender, EventArgs e)
{
string filename = string.Empty;
string FilePath = ConfigurationManager.AppSettings["FilePath"].ToString();
if (FileUpload1.HasFile)
{
string[] Exe = { ".txt" };
string FileExt = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
bool isValidFile = Exe.Contains(FileExt);
if (isValidFile)
{
int FileSize = FileUpload1.PostedFile.ContentLength;
if (FileSize <= 102400)
{
filename = Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(Server.MapPath(FilePath) + filename);
StreamReader sr = new StreamReader(FilePath+filename);
//The error shows up here and i have tried to use FilePath as the single parameter too
int counter = 0;
string delim = " ,.?!";
string[] fields = null;
string line = null;
while (!sr.EndOfStream)
{
line = sr.ReadLine();//each time you read a line you should split it into the words
line.Trim();
fields = line.Split(delim.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
counter += fields.Length; //and just add how many of them there is
}
sr.Close();
lblcount.Text = counter.ToString();
lblMsg.Text = "File upload successfully!";
}
else
{
lblMsg.Text = "File Size allowed upto 100kb!";
}
}
else
{
lblMsg.Text = "Please Upload a text File!";
}
}
else
{
lblMsg.Text = "Please upload a file!";
}
}
}
Can this be sorted out ??
Thanks in Advance!

Use Path.Combine to build paths:
string path = Path.Combine(Server.MapPath(FilePath), filename);
FileUpload1.SaveAs(path);
using(StreamReader sr = new StreamReader(path))
{
// ...
}

Related

how can i upload file to server in asp.net

I have 2 pages send.aspx and recive.aspx.
In send.aspx, I have FileUpload and Button that send selected file to recive.aspx page.
In below you can see recive.aspx.cs code in Page_Load
at the end .
How can I send file to this page?
protected void Page_Load(object sender, EventArgs e)
{
string action = Request.Params["action"];
if (action == null)
{
Response.StatusCode = 400;
Response.End();
}
if (action.Equals("upload"))
{
HttpPostedFile file = Request.Files["file"];
if (file != null && file.ContentLength > 0)
{
//string guid = Guid.NewGuid().ToString();
string ext = Path.GetExtension(file.FileName);
//2- Get and check file extension
string[] validExtesions = { ".e", ".jpg", ".gif", ".png", ".rar",
".zip",".3gp",".3gpp",".mp4",".mov",".wmv",".avi", "",".jpeg", ".mp3", ".ogg"};
if (Array.IndexOf(validExtesions, ext.ToLower()) < 0)
{
Response.Write("Invalid file extension!");
Response.End();
}
//3- Get and check file size
long fileSize = file.ContentLength;
fileSize /= 1024;
if (fileSize > 2048000)
{
Response.Write("Fiele size must be < 2GB");
Response.End();
}
//4- Get file name
string fileName = Path.GetFileName(file.FileName);
//5- Check file exist and if (true) generate new name
while (File.Exists(Path.Combine(UploadFolder, fileName)))
fileName = "1" + fileName;
string fname = fileName;
string path = Server.MapPath(Path.Combine(UploadFolder, fname));
file.SaveAs(path);
Response.Write(fname);
Response.End();
}
else
{
Response.StatusCode = 400;
Response.End();
}
}
}

bulk data export to excel and download in ashx file

I have an asp.net application in which I have a js file and an ashx file. Here in a download button click Im calling handler file in ajax call and retrieving sql table data in a json formatted string/data table and Im trying to export json formated string/data table to excel/csv file and download it. Please help me to find a solution. (Need a solution which help to export large amount of data and download)
I tried the below code but its not downloading excel file.
public void ProcessRequest(HttpContext context)
{
context.Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");
context.Response.ContentType = "application/csv";
HttpResponse response = context.Response;
string exportContent = ExportToSpreadsheet(JsonStringToDataTable(GetDataFromTable()),'excelfilename');
response.Write(exportContent);
context.Response.End();
}
public DataTable JsonStringToDataTable(string jsonString)
{
DataTable dt = new DataTable();
string[] jsonStringArray = Regex.Split(jsonString.Replace("[", "").Replace("]", ""), "},{");
List<string> ColumnsName = new List<string>();
foreach (string jSA in jsonStringArray)
{
string[] jsonStringData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ",");
foreach (string ColumnsNameData in jsonStringData)
{
try
{
int idx = ColumnsNameData.IndexOf(":");
string ColumnsNameString = ColumnsNameData.Substring(0, idx - 1).Replace("\"", "");
if (!ColumnsName.Contains(ColumnsNameString))
{
ColumnsName.Add(ColumnsNameString);
}
}
catch (Exception ex)
{
//throw new Exception(string.Format(ex.Message + "Error Parsing Column Name : {0}", ColumnsNameData));
throw ex;
}
}
break;
}
foreach (string AddColumnName in ColumnsName)
{
dt.Columns.Add(AddColumnName);
}
foreach (string jSA in jsonStringArray)
{
string[] RowData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ",");
DataRow nr = dt.NewRow();
foreach (string rowData in RowData)
{
try
{
int idx = rowData.IndexOf(":");
string RowColumns = rowData.Substring(0, idx - 1).Replace("\"", "");
string RowDataString = rowData.Substring(idx + 1).Replace("\"", "");
nr[RowColumns] = RowDataString;
}
catch (Exception ex)
{
continue;
}
}
dt.Rows.Add(nr);
}
return dt;
}
private static string GetDataFromTable()
{
string returnValue = string.Empty;
var serializer = new JavaScriptSerializer { MaxJsonLength = Int32.MaxValue };
try
{
var result = //get data from sql table;
returnValue = serializer.Serialize(result);
}
catch (Exception e)
{
returnValue = serializer.Serialize(e.Message);
}
return returnValue;
}
public string ExportToSpreadsheet(DataTable table, string name)
{
string res = string.Empty;
try
{
//var resp = Response;
System.Web.HttpResponse resp = System.Web.HttpContext.Current.Response;
resp.Clear();
if (table != null)
{
foreach (DataColumn column in table.Columns)
{
resp.Write(column.ColumnName + ",");
}
}
resp.Write(Environment.NewLine);
if (table != null)
{
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
resp.Write(row[i].ToString().Replace(",", string.Empty) + ",");
}
resp.Write(Environment.NewLine);
}
}
res = "successfully downloaded";
resp.ContentType = "text/csv";
resp.AppendHeader("Content-Disposition", "attachment; filename=" + name + ".csv");
// resp.End();
}
catch(Exception ex)
{
res = ex.Message;
}
return res;
}
Start using a specialized libary like EPPlus. It will create real Excel files.
private void exportToExcel(DataTable dataTable)
{
using (ExcelPackage excelPackage = new ExcelPackage())
{
//create the worksheet
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("Sheet 1");
//load the datatable into the sheet, with headers
worksheet.Cells["A1"].LoadFromDataTable(dataTable, true);
//send the file to the browser
byte[] bin = excelPackage.GetAsByteArray();
Response.ClearHeaders();
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-length", bin.Length.ToString());
Response.AddHeader("content-disposition", "attachment; filename=\"ExcelDemo.xlsx\"");
Response.OutputStream.Write(bin, 0, bin.Length);
Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}

asp.net upload control is not working in ipad

The asp.net upload control is uploading the file for first time in Ipad but not after that and not even showing any error
The code is as below
protected void UploadThisFile(FileUpload upload)
{
try
{
string folderpath = ConfigurationManager.AppSettings["BTCommDynamic"].ToString() + ConfigurationManager.AppSettings["Attachments"].ToString();
Guid fileguid = Guid.NewGuid();
string filename = fileguid + upload.FileName;
if (upload.HasFile && dtFiles != null)
{
DataRow drFileRow = dtFiles.NewRow();
drFileRow["FileName"] = upload.FileName;
string theFileName = Path.Combine(Server.MapPath(folderpath), filename);
string theFileName1 = Path.Combine(folderpath, filename);
//string theFileName = folderpath;
//to save the file in specified path
upload.SaveAs(theFileName);
drFileRow["FilePath"] = theFileName1;
double Filesize = (upload.FileContent.Length);
if (Filesize > 1024)
{
drFileRow["FileSize"] = (upload.FileContent.Length / 1024).ToString() + " KB";
}
else
{
drFileRow["FileSize"] = (upload.FileContent.Length).ToString() + " Bytes";
}
dtFiles.Rows.Add(drFileRow);
gvAttachment.DataSource = dtFiles;
gvAttachment.DataBind();
}
}
catch (Exception ex)
{
string message = Utility.GetExceptionMessage(ex.GetType().ToString(), ex.Message);
Display_Message(message);
}
}
Do you use firebug? There might be an error on a client side that prevents the work of your functionality.
Do you have any logic on your client side? Some kinda jquery/ajax calls?

Web Application not able to Delete files for Read/Write Enabled Folders in ASP.NET

When I'm trying to delete the images uploaded by me via website named "SampleApplication" I can see the following error shown in Stack Trace
The process cannot access the file 'D:\Hosting\123456\html\App_Images\myfolder1\eKuK2511.png' because it is being used by another process.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.IO.IOException: The process cannot access the file 'D:\Hosting\123456\html\App_Images\myfolder1\eKuK2511.png' because it is being used by another process.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[IOException: The process cannot access the file 'D:\Hosting\123456\html\App_Images\myfolder1\eKuK2511.png' because it is being used by another process.]
System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) +9723350
System.IO.File.Delete(String path) +9545728
SampleApplication.BasePage.DeleteApp_ImagesById(DataTable dt) +503
SampleApplication.PostLease.MyAccount.DeleteAd_Property(Object sender, EventArgs e) +193
System.Web.UI.WebControls.LinkButton.OnClick(EventArgs e) +118
System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument) +113
System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +9
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +176
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272
The folder App_Images has been given Read/write Permission and inherits to child folders namely myfolder1, myfolder2, myfolder3, myfolder4. Even when I tried to forcefully delete the image eKuK2511.png from the FTP File manager it is showing the following error:
550 The process cannot access the file because it is being used by another process.
How to getrid of this error?
Edit:
Upload Code:
public void UploadImages()
{
if (ServerSideValidation() == true)
{
string SavePath;
ImgPaths = new List<string>();
// Get the HttpFileCollection
HttpFileCollection hfc = Request.Files;
if (hfc.Count > 0)
{
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
#region trials compression.
SavePath = "~/App_Images/" + Session["AppContext"].ToString() + "/" + GetUniqueKey() + GetFileExtension(hpf.FileName);
SaveImageByCompressing(hpf, SavePath);
#endregion
//SavePath can be saved in DB.
ImgPaths.Add(SavePath);
//Save Thumbnail Image.
if (i == 0)
{
string savedName = "Thumb_" + GetUniqueKey() + GetFileExtension(AppDomain.CurrentDomain.BaseDirectory + ImgPaths[0].ToString().Replace("~/", "\\").Replace("/", "\\"));
SavePath = "~/App_Images/" + Session["AppContext"].ToString() + "/" + savedName;
SaveThumbImage(AppDomain.CurrentDomain.BaseDirectory + ImgPaths[0].ToString().Replace("~/", "").Replace("/", "\\"), AppDomain.CurrentDomain.BaseDirectory + "App_Images\\" + Session["AppContext"].ToString() + "\\" + savedName, 75, 75);
ImgPaths.Add(SavePath);
}
}
}
Session.Remove("AppContext");
lblMsg.Text = "Images Uploaded Successfully.";
//ShowUploadedImages(ImgPaths);
}
else
{
lblMsg.Text = "Images uploaded are either in wrong format or were deleted after uploading.";
}
}
else
{
lstPaths = new List<string>();
lblMsg.Text = "No Images Uploaded";
}
}
private void SaveImageByCompressing(HttpPostedFile hpf, string filePath)
{
Image imgFromClient = Image.FromStream(hpf.InputStream);
string SavetoFullPath = AppDomain.CurrentDomain.BaseDirectory + filePath.Replace("~/", "").Replace("/", "\\");
Image.GetThumbnailImageAbort myCallbackCompressed = new Image.GetThumbnailImageAbort(ThumbnailCallback);
Image imageToSave= imgFromClient.GetThumbnailImage(imgFromClient.Width, imgFromClient.Height, myCallbackCompressed, IntPtr.Zero);
imageToSave.Save(SavetoFullPath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
public static void SaveThumbImage(string imagePath, string filePath, int width = 0, int height = 0)
{
Image originalImage = Image.FromFile(imagePath);
if (width > 0 && height > 0)
{
Image.GetThumbnailImageAbort myCallback = new Image.GetThumbnailImageAbort(ThumbnailCallback);
Image imageToSave = originalImage.GetThumbnailImage(width, height, myCallback, IntPtr.Zero);
imageToSave.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
else
{
originalImage.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
private static bool ThumbnailCallback() { return false; }
private bool ServerSideValidation()
{
string errorMsg = string.Empty, temp = null;
bool errorFlag = true;
// Get the HttpFileCollection
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0 && hpf.FileName!=String.Empty)
{
temp = ValidateImage(hpf);
if (temp != null)
{
errorMsg += GetFileName(hpf.FileName.ToString()) + " has error : " + temp;
temp = null;
}
}
else
{
return false;
}
}
if (!string.IsNullOrWhiteSpace(errorMsg))
{
lblMsg.Text = errorMsg;
errorFlag = false;
}
return errorFlag;
}
private string GetFileExtension(string filePath)
{
FileInfo fi = new FileInfo(filePath);
return fi.Extension;
}
private string GetFileName(string filePath)
{
FileInfo fi = new FileInfo(filePath);
return fi.Name;
}
private string GetUniqueKey()
{
int maxSize = 8;
char[] chars = new char[62];
string a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
chars = a.ToCharArray();
int size = maxSize;
byte[] data = new byte[1];
RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
crypto.GetNonZeroBytes(data);
size = maxSize;
data = new byte[size];
crypto.GetNonZeroBytes(data);
StringBuilder result = new StringBuilder(size);
foreach (byte b in data)
{
result.Append(chars[b % (chars.Length - 1)]);
}
return Session["AppContext"].ToString() + Page.User.Identity.Name.ToString() + result.ToString();
}
private string ValidateImage(HttpPostedFile myFile)
{
string msg = null;
//6MB
int FileMaxSize = 6291456;
//Check Length of File is Valid or Not.
if (myFile.ContentLength > FileMaxSize)
{
msg = msg + "File Size is Too Large. You are allowed only a maximum of 6MB per Image.";
}
//Check File Type is Valid or Not.
if (!IsValidFile(myFile.FileName))
{
msg = msg + "Invalid File Type.";
}
return msg;
}
private bool IsValidFile(string filePath)
{
bool isValid = false;
string[] fileExtensions = { ".BMP", ".JPG", ".PNG", ".GIF", ".JPEG" };
for (int i = 0; i < fileExtensions.Length; i++)
{
if (filePath.ToUpper().Contains(fileExtensions[i]))
{
isValid = true; break;
}
}
return isValid;
}
Delete Code:
/// <summary>
/// Delete all images. If there are no Images then by default NoImage.png is assigned. So skip deleting that image.
/// </summary>
/// <param name="dt"></param>
protected void DeleteApp_ImagesById(DataTable dt)
{
if (dt.Rows[0][0].ToString() != "~/images/NoImage.png")
{
for (int i = 0; i < dt.Columns.Count; i++)
{
if (dt.Rows[0][i].ToString() != string.Empty)
{
string str = Regex.Replace(dt.Rows[0][i].ToString(), "~/", "");
File.Delete(Request.PhysicalApplicationPath.ToString() + Regex.Replace(str, "/", "\\").ToString());
}
}
}
}
The docs on MSDN about Image.Save say that the file remains locked until the Image is disposed.
So I suppose that changing the code that save the images in this way
private void SaveImageByCompressing(HttpPostedFile hpf, string filePath)
{
using(Image imgFromClient = Image.FromStream(hpf.InputStream))
{
string SavetoFullPath = AppDomain.CurrentDomain.BaseDirectory +
filePath.Replace("~/", "").Replace("/", "\\");
Image.GetThumbnailImageAbort myCallbackCompressed =
new Image.GetThumbnailImageAbort(ThumbnailCallback);
using(Image imageToSave= imgFromClient.GetThumbnailImage(imgFromClient.Width,
imgFromClient.Height, myCallbackCompressed, IntPtr.Zero))
{
imageToSave.Save(SavetoFullPath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
public static void SaveThumbImage(string imagePath, string filePath,
int width = 0, int height = 0)
{
using(Image originalImage = Image.FromFile(imagePath))
{
if (width > 0 && height > 0)
{
Image.GetThumbnailImageAbort myCallback =
new Image.GetThumbnailImageAbort(ThumbnailCallback);
using(Image imageToSave = originalImage.GetThumbnailImage(width, height,
myCallback, IntPtr.Zero))
{
imageToSave.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
else
{
originalImage.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
is a safe way to ensure your images are immediately unlocked when you finish with the upload code

How to get the data of a specific column from an excel file?

Hi I've an excel file which looks like this
id name age phne no and like this i have 35 columns.........
I'm using a webapplication for this in which I've a fileupload control,a button and two textboxes
fileuploadcontrol
button
textbox1
textbox2
Now when I upload the excel file on button click it should read complete file .........
and when I enter the required column in the textbox1 I get those column details only its like this
textbox1(c1,c4,c5,c30) I sholud get only those column details and in the other text box if I enter the location to be saved it should be saved in that location can any one help me with this I had finished till file uploading and reading.....all I need is how to evaluate those textboxes to get my required data
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
if (FileUpload1.PostedFile.ContentType == "application/xlsx")
{
path = Server.MapPath(".") + "\\inputfiles\\" + Guid.NewGuid() + FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(path);
Label1.Text = "File Uploaded Successfully...";
StreamReader reader = new StreamReader(FileUpload1.FileContent);
string text = reader.ReadToEnd();
}
else
Label1.Text = "Upload .xlsx File";
}
else
Label1.Text = "Upload file";
}
Check this:
Read and Display Data From an Excel File (.xsl or .xlsx) in ASP.NET
You can specify what columns you need to read on select query.
Regards
I got the answer myself .......ty for tryin to helpin me m postin my code if any needs in any case........
protected void btns_Click(object sender, EventArgs e)
{
string path = string.Empty;
location = Textbox2.Text;
if (fup1.HasFile)
{
try
{
path = Server.MapPath(".") + "\\uploadedfiles\\" + Guid.NewGuid() + fup1.FileName;
fup1.PostedFile.SaveAs(path);
lbl5.Text = "Upload status: File uploaded!";
}
catch (Exception ex)
{
lbl5.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
excelfile(path);
}
}
void excelfile( string path)
{
string readfile = path;
// initialize the Excel Application class
Excel.Application app = new Excel.Application();
//Excel.Worksheet NwSheet;
Excel.Range ShtRange;
// create the workbook object by opening the excel file.
Excel.Workbook workBook = app.Workbooks.Open(readfile, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
// Get The Active Worksheet Using Sheet Name Or Active Sheet
Excel.Worksheet workSheet = (Excel.Worksheet)workBook.ActiveSheet;
int index = 1;
System.Text.StringBuilder sb = new StringBuilder();
try
{
string[] values = Textbox1.Text.Split(new char[] { ',' });
int[] colindexs = new int[values.Length];
for (int i = 0; i < values.Length; i++)
{
colindexs[i] = Convert.ToInt16(values[i]);
}
while (((Excel.Range)workSheet.Cells[index, 1]).Value2 != null)
{
string str = "";
foreach (int col1 in colindexs)
{
str = str + Convert.ToString(((Excel.Range)workSheet.Cells[index, col1]).Value2) + ",";
}
str = str.Substring(0, str.Length - 1);
sb.Append(str);
sb.Append(Environment.NewLine);
index++;
}
Writetofile(sb.ToString());
ShtRange = workSheet.UsedRange;
}
catch (Exception ex)
{
app.Quit();
lbl5.Text=ex.Message;
}
}
void Writetofile(string content)
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(location, true))
{
sw.Write(content);
sw.Flush();
}
}
}

Resources