select particular key by name from HttpFileCollection - httpfilecollection

how to select particular item from HttpFileCollection Object
HttpFileCollection uploads = default(HttpFileCollection);
uploads = HttpContext.Current.Request.Files;
I want to select some keys from uploads

If I understand you need
if (context != null)
{
if (context.Request.Files.Count > 0)
{
var file0 = context.Request.Files[0];
var file1 = context.Request.Files[1];
}
}

Related

How to use Tempdata to display the list

I have did the excel upload in dotnet core .I had to use tempdata to retrieve the details of the excel in list.Instead in my below code i had used Static object to retrieve the list.My code works as like this ,when i click on upload button it will display the details in the excel sheet.and when click on save it will save it to database and i need to edit in grid view using ajax call also .Help me out
My Action in controller is
public async Task<IActionResult> ImportEmployeeDetails(IFormFile excelfile)
{
try
{
EmployeesViewModelList employeesListObject = new EmployeesViewModelList();
List<EmployeeModel> employeesViewModelList = new List<EmployeeModel>();
if (excelfile == null || excelfile.Length == 0)
{
return View(employeesListObject);
}
var supportedTypes = new[] { ".xls", ".xlsx" };
var ext = Path.GetExtension(excelfile.FileName);
if (!supportedTypes.Contains(ext))
{
return View(employeesListObject);
}
var path = Path.Combine(
Directory.GetCurrentDirectory(), "wwwroot",
"EmployeeDetails.xlsx");
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
using (var stream = new FileStream(path, FileMode.Create))
{
await excelfile.CopyToAsync(stream);
}
FileInfo file = new FileInfo(path);
using (ExcelPackage package = new ExcelPackage(file))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
int rowCount = worksheet.Dimension.Rows;
int ColCount = worksheet.Dimension.Columns;
for (int i = 2; i <= rowCount; i++)
{
EmployeeModel emp = new EmployeeModel();
emp.EmployeeId = Convert.ToInt32(worksheet.Cells[i, 1].Value.ToString());
emp.EmpFirstName = worksheet.Cells[i, 2].Value.ToString();
employeesViewModelList.Add(emp);
}
employeesListObject.EmpModelList = employeesViewModelList;
return View(employeesListObject);
}
}
catch(Exception ex)
{
TempData["Message"] = "Opps! Something Went wrong!";
return RedirectToAction("ExcelPackage");
}
}
Try this, using your own list.
List<string> SomeList = new List<string>();
TempData["MyList"] = SomeList;
//then to get data just do
SomeList = TempData["MyList"] as List<string>; //This converts back to List<T>
Once you add the list to the TempData, you can retrive it from any Action or View in the same controller

Filebytes for multiple fileuploads

I have a form with a multiple fileupload on. (You can select multiple files within the same filecontrol
These files I have to upload to an API
If I don't have a multiple, but a single fileupload, I can do
byte[] filedata = FileUploadControl.FileBytes;
String filestring = Convert.ToBase64String(filedata);
If have multiple fileupload, I can use this to iterate over the files:
HttpFileCollection fileCollection = Request.Files;
for (int i = 0; i < fileCollection.Count; i++)
{
HttpPostedFile uploadfile = fileCollection[i];
if (uploadfile.ContentLength > 0)
{
Int32 ContentLength = uploadfile.ContentLength;
String ContentType = uploadfile.ContentType;
string filename = uploadfile.FileName;
}
}
But I don't have uploadfile.FileBytes
How can I get the contents of the file to a string?
I got it to work like this:
HttpFileCollection fileCollection = Request.Files;
for (int i = 0; i < fileCollection.Count; i++)
{
HttpPostedFile uploadfile = fileCollection[i];
if (uploadfile.ContentLength > 0)
{
...
MemoryStream ms = new MemoryStream(uploadfile.ContentLength);
uploadfile.InputStream.CopyTo(ms);
String filestring = Convert.ToBase64String(ms.ToArray());
...
}
}

DataTable Retrieves another DataTable Information?

I Have an Exception in my Live Application..DataTable Retrives another DataTable information..
if (HttpContext.Current.User != null)
{
if (Session["username"] != null)
{
string pageName = Page.Page.AppRelativeVirtualPath.Substring(Page.Page.AppRelativeVirtualPath.LastIndexOf('/') + 1);
DataTable dtFeatures2 = new DataTable();
dtFeatures2.Clear();
objMatermenuPL.usertype = Session["UserType"].ToString();
dtFeatures2 = objMastermenuBAL.GetMastermenu(objMatermenuPL);
DataView dt = new DataView(dtFeatures2);
dt.Sort = "fld_feature ASC";
if (dtFeatures2 != null)
{
foreach (Control control in leftpanel.Controls)
{
Type ty = control.GetType();
if (ty.Name.ToUpper() == "HTMLANCHOR")
{
int i = dt.Find(control.ID.Substring(3));
if (i < 0 && control.ID.Contains("lnk"))
control.Visible = false;
if (control.ID.Contains("lnk") && control.ID.Substring(3) + ".aspx" == pageName)
{
HtmlAnchor a = (HtmlAnchor)control;
a.Attributes.Add("class", "active");
}
}
}
}
}
}
else
{
Response.Redirect("~/Login.aspx");
}
This code we use All most all master pages...If an exception Raise,then it comes directly
this line..
dtFeatures2 = objMastermenuBAL.GetMastermenu(objMatermenuPL);
Message like : Cannot find column fld_feature.
"dtFeatures2" is Filled With Before Opened Page DataTable Information...
This exception gone after some..It's Working Fine 100%....Some times only shows these exception...What happend Here........

how to delete files from a folder according to date

private void DeleteFiles()
{
DirectoryInfo di = new DirectoryInfo("E:\\test");
var files = di.GetFiles();
var maxFile = files.Max(r => r.Length);
foreach (FileInfo file in files.Where(r => r.Length < maxFile))
{
file.Delete();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
this.DeleteFiles();
}
in this code i delete file according to size now what i want is i want to delete file according to date also
for ex: suppose i create 5 file yesterday and 5 file today now i want to delete all the files except who's size is largest for both days how can i do that.
Thanks in advance
you can get the time like this
DateTime creationTime = File.GetCreationTime(#"c:\file.txt");
DateTime lastWriteTime = File.GetLastWriteTime(#"c:\file.txt");
DateTime lastAccessTime = File.GetLastAccessTime(#"c:\file.txt");
http://www.csharp-examples.net/file-creation-modification-time/
also compare the time using DateTime.Compare
http://msdn.microsoft.com/en-us/library/system.datetime.compare.aspx
You can select files based on FileInfo.CreationTime property and then select those files like:
private void DeleteFiles()
{
DirectoryInfo di = new DirectoryInfo("E:\\test");
var files = di.GetFiles();
var maxFile = files.Max(r => r.Length);
DateTime startDate = DateTime.Now.Date.AddDays(-1);
DateTime endDate = DateTime.Now.Date;
var filesToBeDeleted = files.Where(r=> (r.Length < maxFile)
&& (r.CreationTime >= startDate &&
r.CreationTime <= endDate));
foreach (FileInfo file in filesToBeDeleted)
{
file.Delete();
}
}
You can make the selection based on other DateTime properties with FileInfo like, LastWriteTime, also you can specify your own start and end date for your criteria.

Converting HttpFileCollection to byte and stream the data to Image Control in asp.net

HttpFileCollection oHttpFileCollection = e.PostedFiles;
HttpPostedFile oHttpPostedFile = null;
if (e.HasFiles)
{
for (int n = 0; n < e.Count; n++)
{
oHttpPostedFile = oHttpFileCollection[n];
if (oHttpPostedFile.ContentLength <= 0)
continue;
else
oHttpPostedFile.SaveAs(Server.MapPath("Files") + "\\" + System.IO.Path.GetFileName(oHttpPostedFile.FileName));
}
How can I convert HttpFileCollection to byte and read the stream and then display the image to Image Control in asp.net
Thanks
HttpFileCollection oHttpFileCollection = e.PostedFiles;
HttpPostedFile oHttpPostedFile = null;
if (e.HasFiles)
{
for (int n = 0; n < e.Count; n++)
{
oHttpPostedFile = oHttpFileCollection[n];
if (oHttpPostedFile.ContentLength <= 0)
{
continue;
}
else
{
var filename = Path.GetFileName(oHttpPostedFile.FileName);
var path = Path.Combine(Server.MapPath("~/Files/"), filename);
oHttpPostedFile.SaveAs(path);
// Now you could display each image in a dynamically added Image
// control to the page:
Image image = new Image();
image.ImageUrl = "~/Files/" + filename;
// I assume that you have a reference to the current page
// so that you could append image controls to it.
// You could also append the images to a placeholder or a Panel
// on your WebForm
this.Controls.Add(image);
}
}

Resources