public ActionResult Import(HttpPostedFileBase currencyConversionsFile)
{
string filename = "CurrencyConversion Upload_" + DateTime.Now.ToString("dd-MM-yyyy") + ".csv";
string folderPath = Server.MapPath("~/Files/");
string filePath = Server.MapPath("~/Files/" + filename);
currencyConversionsFile.SaveAs(filePath);
string[] csvData = System.IO.File.ReadAllLines(filePath);
//the later code isn't show here
}
I know the usual way to convert httppostedfilebase to String array, which will store the file in the server first, then read the data from the server. Is there anyway to get the string array directly from the httppostedfilebase with out store the file into the server?
Well you can read your file line by line from Stream like this:
List<string> csvData = new List<string>();
using (System.IO.StreamReader reader = new System.IO.StreamReader(currencyConversionsFile.InputStream))
{
while (!reader.EndOfStream)
{
csvData.Add(reader.ReadLine());
}
}
From another thread addressing the same issue, this answer helped me get the posted file to a string -
https://stackoverflow.com/a/40304761/5333178
To quote,
string result = string.Empty;
using (BinaryReader b = new BinaryReader(file.InputStream))
{
byte[] binData = b.ReadBytes(file.ContentLength);
result = System.Text.Encoding.UTF8.GetString(binData);
}
Splitting the string into an array -
string[] csvData = new string[] { };
csvData = result.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
Related
I'm trying to figure out how to join two strings that are encoded Base64 and then decode and get the combined result.
Example:
string1 Hello --- string1 Base64 SGVsbG8=
string2 World --- string2 Base64 V29ybGQ=
If I join the base64 I get something that wont decode SGVsbG8=V29ybGQ=
I want the result to say: Hello World
I don't want only this example to work but rather something that will work with any string.
This is a very simplified problem which is a step on an application I'm trying to write I'm stuck on.
What if you encode both strings to array, then combine those arrays and finally GetString from the bytes?
using System;
using System.Text;
using System.Linq;
public class Program
{
public static void Main()
{
var base1 = "SGVsbG8=";
var base2 = "V29ybGQ=";
var array1 = Convert.FromBase64String(base1);
var array2 = Convert.FromBase64String(base2);
var comb = Combine(array1, array2);
var data = Encoding.Default.GetString(comb);
Console.WriteLine(data);
}
private static byte[] Combine(byte[] first, byte[] second)
{
return first.Concat(second).ToArray();
}
}
I found a best way to do this, add plus between one string and other, and add ONE, and only ONE equals char ('=') at the end of string. The return will be "Hello>World", then remove the ">":
class Program
{
static void Main(string[] args)
{
string base64String = "SGVsbG8+V29ybGQ=";
byte[] encodedByte = Convert.FromBase64String(base64String);
var finalString = Encoding.Default.GetString(encodedByte)).Replace(">", " ");
Console.WriteLine(finalString.ToString());
}
}
(Old way) In C# I do something like this:
class Program
{
static void Main(string[] args)
{
string base64String = "SGVsbG8=V29ybGQ=";
Console.WriteLine(DecodeBase64String(base64String));
Console.ReadLine();
}
public static string DecodeBase64String(string base64String)
{
StringBuilder finalString = new StringBuilder();
foreach (var text in base64String.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries))
{
byte[] encodedByte = Convert.FromBase64String(text + "=");
finalString.Append(Encoding.Default.GetString(encodedByte));
finalString.Append(" "); //This line exists only to attend the "Hello World" case. The correct is remove this and let the one that will receive the return to decide what will do with returned string.
}
return finalString.ToString();
}
}
I'm uploading an image to my site using the following code,
The Image uploading just fine but, how ever
I need to fix the following things :
-I'm getting this kind of Url
C:\Users\Me\Documents\Visual Studio 2013\Projects\Wow\WowMvc5\WowMvc5\images\gallery\Picture 022.jpg,
Instead of relevant folder Url
-I thing in order to avoid an error of 2 images this the same name it would be better to create a folder under images for each image (or any better idea )
Thank you for your time
public async Task<ActionResult> Create([Bind(Include = "TakeAwayId,TakeAwayName,description,Price,DishUrl,quantity,DishesAmount,GenreId")] TakeAway takeaway)
{
var path = Server.MapPath("~/Images/gallery/");
foreach (string item in Request.Files)
{
HttpPostedFileBase file = Request.Files[item];
if (file.ContentLength == 0)
{
continue;
}
string SavedFileName = System.IO.Path.GetFileName(file.FileName);
SavedFileName = Server.MapPath
("~" + "/images/gallery/" + SavedFileName);
file.SaveAs(SavedFileName);
takeaway.DishUrl = SavedFileName;
}
if (ModelState.IsValid)
{
db.takeaway.Add(takeaway);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.GenreId = new SelectList(db.genre, "GenreId", "GenreName", takeaway.GenreId);
return View(takeaway);
}
What I would do is name and save each picture using a HashCode.
By definition, It's very improbable that 2 different strings, when transformed using a hash algorithm, will have the same output. Just to be sure, add a random string to the original name of the image.
string newName = (oldName + random).GetHashCode().ToString()
filename_1.jpg
where cnt is incremental count
if(file.exists()
{
string cnt = file.split("");
String newFileName = filename+""+(cnt+1)+".jpg";
}
I am trying to export data as Excel in my C#.Net MVC Application. I have used return file() in Actionresult. The file is returned and downloaded successfully.
But there is error while opening file and the file names gets changed when it is opened.
Downloaded file name is ExportFilterCRMdoctorRequest.xls but after opening it changes to Book1.
code for Exporting file:
public ActionResult ExportFilterCRMdoctorRequest()
{
var stream = new MemoryStream();
var serializer = new XmlSerializer(typeof(List<CDRFilterCRMDoctorRequest>));
//We load the data
List<CDRFilterCRMDoctorRequest> data = (List<CDRFilterCRMDoctorRequest>)Session["filterCRMRequestList"]; //Retriving data from Session
//We turn it into an XML and save it in the memory
serializer.Serialize(stream, data);
stream.Position = 0;
//We return the XML from the memory as a .xls file
return File(stream, "application/vnd.ms-excel", "ExportFilterCRMdoctorRequest.xls");
}
This is called Extension Hardening. Execute steps to avoid this error.
Open your Registry (Start -> Run -> regedit.exe) Navigate to
HKEY_CURRENT_USER\SOFTWARE\MICROSOFT\OFFICE\12.0\EXCEL\SECURITY
Right click in the right window and choose New -> DWORD Type
“ExtensionHardening” as the name (without the quotes)
Verify that the data has the value “0″
NOTE
There is one thing that has to be borne in mind when serializing in
XML. XML is not Excel’s standard format and it has to open the file as
XML data. This means that when opening the file it will issue a couple
of warnings which are more of a nuisance than anything else.
Back to your original Query : Replicated your issue and below is the fix
Sample Class
public class StudentModel
{
public string Name { get; set; }
public string Address { get; set; }
public string Class { get; set; }
public string Section { get; set; }
}
Sample Data
private List<StudentModel> StudentData()
{
List<StudentModel> objstudentmodel = new List<StudentModel>();
objstudentmodel.Add(new StudentModel { Name = "Name1", Class = "1",
Address = "Address1", Section = "A" });
objstudentmodel.Add(new StudentModel { Name = "Name2", Class = "2",
Address = "Address2", Section = "A" });
return objstudentmodel;
}
Action Method
public ActionResult Index()
{
List<StudentModel> objstudent = new List<StudentModel>();
objstudent = StudentData();
StringBuilder sb = new StringBuilder();
sb.Append("<table border='" + "1px" + "'b>");
//code section for creating header column
sb.Append("<tr>");
sb.Append("<td><b><font size=2>NAME</font></b></td>");
sb.Append("<td><b><font size=2>CLASS</font></b></td>");
sb.Append("<td><b><font size=2>ADDRESS</font></b></td>");
sb.Append("<td><b><font size=2>SECTION</font></b></td>");
sb.Append("</tr>");
//code for creating excel data
foreach (StudentModel item in objstudent)
{
sb.Append("<tr>");
sb.Append("<td><font>" + item.Name.ToString() + "</font></td>");
sb.Append("<td><font>" + item.Class.ToString() + "</font></td>");
sb.Append("<td><font>" + item.Address.ToString() + "</font></td>");
sb.Append("<td><font>" + item.Section.ToString() + "</font></td>");
sb.Append("</tr>");
}
sb.Append("</table>");
HttpContext.Response.AddHeader("content-disposition",
"attachment; filename=student_" +
DateTime.Now.Year.ToString() + ".xls");
this.Response.ContentType = "application/vnd.ms-excel";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
return File(buffer, "application/vnd.ms-excel");
}
Say my current page url has got (http://mysite/english/faq.aspx?faqid=12123&cid=4545&intcid=65456&h=man)
string excludeQuerystring = DynConfig.Item("GoogleSEOLinkSettings/ExcludeQuerystring"); //this is the list of my exclude querystring (cid,intcid,del)
querystring = HttpContext.Current.Request.Url.AbsoluteUri.Split('?')[1]; //I will get faqid=12123&cid=4545,intcid=65456
StringBuilder fullQueryString = new StringBuilder();
if (!string.IsNullOrEmpty(excludeQuerystring) && !string.IsNullOrEmpty(querystring))
{
string[] strEQ = excludeQuerystring.Split(','); //making a array of excluded querystrings
NameValueCollection navValues = HttpUtility.ParseQueryString(querystring); //getting the list of querystring in NameValueCollection
if (navValues.Count > 0)
{
string[] strQ = navValues.AllKeys;
if(strQ.Length>0)
{
}
}
}
querystring= ?+faqid=12123&h=man //here I want updated querystring which does not have any querystring which is there in my excludeQuerystring
I am confused how to get this, actually I want to make a function which will do this all.
Please suggest!!
EDIT:
I applied new code to resolve above problem, however got little stuck while converting NameValueCollection to querystring again.
protected void Page_Load(object sender, EventArgs e)
{
string querystring = string.Empty;
string excludeList = "cid,intcid,del";
if (!string.IsNullOrEmpty(excludeList))
{
string getFinalString = GetQueryString(excludeList);
getFinalString = "?" + getFinalString;
}
}
public string GetQueryString(string excludeArray)
{
string retQueryString = string.Empty;
if (excludeArray.IndexOf(",") != -1)
{
string[] strArray = excludeArray.Split(",".ToCharArray());
NameValueCollection filtered = new NameValueCollection();
filtered.Add(HttpUtility.ParseQueryString(Request.Url.Query));
if (filtered.HasKeys())
{
foreach (string strMatch in strArray)
{
filtered.Remove(strMatch);
}
retQueryString = filtered.ToString(); //Here I am not able to convert back to querystring, however there are other ways to get it like (http://leekelleher.com/2008/06/06/how-to-convert-namevaluecollection-to-a-query-string/), is there any other way to do that
}
}
return retQueryString;
}
Below is the perfect solution I got it, any comments on this.
string excludeList = "cid,intcid,del";
string getFinalString = Regex.Replace(Regex.Replace(Regex.Replace(Request.Url.Query, #"^\?", "&"), "&(" + excludeList.Replace(",", "|") + ")=[^&]*", "", RegexOptions.IgnoreCase), "^&", "?");
We cannot delete a query string directly like below:
Request.QueryString.Remove("foo")
If you do this, you will get an error - collection is read-only. So, we need to write the below code before deleting the query string.
In C#:
PropertyInfo isreadonly =
typeof(System.Collections.Specialized.NameValueCollection).GetProperty(
"IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
// make collection editable
isreadonly.SetValue(this.Request.QueryString, false, null);
// remove
this.Request.QueryString.Remove("foo");
Hope this will help you !!
yes there is a way to compare two arrays
var array1 = new byte[] { 1, 2, 5, 4 };
var array2 = new byte[] { 1, 2, 3, 4 };
var areEqual = array1.SequenceEqual(array2); //return boolean value True or False
Read a Text file having any line starts from "//" omit this line and moved to next line.
The Input text file having some seprate partitions. Find line by line process and this mark.
If you are using .Net 3.5 you can use LINQ with a IEnumerable wrapped around a Stream Reader. This cool part if then you can just use a where statement to file statmens or better yet use a select with a regular expression to just trim the comment and leave data on the same line.
//.Net 3.5
static class Program
{
static void Main(string[] args)
{
var clean = from line in args[0].ReadAsLines()
let trimmed = line.Trim()
where !trimmed.StartsWith("//")
select line;
}
static IEnumerable<string> ReadAsLines(this string filename)
{
using (var reader = new StreamReader(filename))
while (!reader.EndOfStream)
yield return reader.ReadLine();
}
}
...
//.Net 2.0
static class Program
{
static void Main(string[] args)
{
var clean = FilteredLines(args[0]);
}
static IEnumerable<string> FilteredLines(string filename)
{
foreach (var line in ReadAsLines(filename))
if (line.TrimStart().StartsWith("//"))
yield return line;
}
static IEnumerable<string> ReadAsLines(string filename)
{
using (var reader = new StreamReader(filename))
while (!reader.EndOfStream)
yield return reader.ReadLine();
}
}
I'm not sure what you exactly need but, if you just want to filter out // lines from some text in a stream... just remember to close the stream after using it.
public string FilterComments(System.IO.Stream stream)
{
var data = new System.Text.StringBuilder();
using (var reader = new System.IO.StreamReader(stream))
{
var line = string.Empty;
while (!reader.EndOfStream)
{
line = reader.ReadLine();
if (!line.TrimStart(' ').StartsWith("//"))
{
data.Append(line);
}
}
}
return data.ToString();
}
Class SplLineIgnorStrmReader:StreamReader // derived class from StreamReader
SplLineIgnorStrmReader ConverterDefFileReadStream = null;
{
//created the Obj for this Class.
Obj = new SplLineIgnorStrmReader(strFile, Encoding.default);
}
public override string ReadLine()
{
string strLineText = "", strTemp;
while (!EndOfStream)
{
strLineText = base.ReadLine();
strLineText = strLineText.TrimStart(' ');
strLineText = strLineText.TrimEnd(' ');
strTemp = strLineText.Substring(0, 2);
if (strTemp == "//")
continue;
break;
}
return strLineText;
This is if u want to read the Text file and omit any comments from that file(here exclude "//" comment).