convert byte[] to string when upload a file in asp.net - asp.net

I have uploaded a file(image) by asp.net.
here is my code:
string imgpathpic =Convert .ToString (Session["imgpathpic"]);
long sizepic =Convert .ToInt64 (Session["sizepic"]);
string extpic = Convert.ToString(Session["extpic"]);
byte[] inputpic = new byte[sizepic - 1];
inputpic = FileUpload2.FileBytes;
for (int loop1 = 0; loop1 < sizepic; loop1++)
{
displayStringPic = displayStringPic + inputpic[loop1].ToString();
}
I converted byte[] to string by that for,but after line displayStringPic = displayStringPic + inputpic[loop1].ToString(); i receive this exception :
Index was outside the bounds of the array.

The loop condition would be on the length of inputpic as you are accessing the element of inputpic in the loop body
for (int loop1 = 0; loop1 < inputpic.Length; loop1++)
{
displayStringPic = displayStringPic + inputpic[loop1].ToString();
}
You should use string builder instead of string for optimum solution when there a lot of string concatenation, see How to: Concatenate Multiple Strings (C# Programming Guide)
StringBuilder sb = new StringBuilder();
foreach(byte b in inputpic)
{
sb.Append(b.ToString());
}
string displayStringPic = sb.ToString();
You better convert the byte array to string using System.Text.Encoding
var str = System.Text.Encoding.UTF8.GetString(result);
Note Aside from converting the byte array to string, you can story the image as Image or in binary format.

Related

Read text file from server and split into multiple file in asp.net

read text file from the server and split into mutiple file in asp.net
for example one text file is located in server which size as 2 mb.
i want to divide this text file into five text file and write into the folder.
public void SplitFile(string Filename, int Parts)
{
string str=File.ReadAllText(Filename);
str = str.Replace("\r\n", "");
int totalScore=str.Length;
int div = totalScore / Parts;
int mod = totalScore % Parts;
string result="";
for (int i = 1; i <= Parts; i++)
{
if (i == Parts)
{
div = div+mod;
}
result = str.Substring(0, div);
str = str.Remove(0, div);
System.IO.File.WriteAllText(Filename.Replace(".", i +"."), result);
}
}

How can I get total size of particular folder in C#?

I'm creating one application where I'm giving certain memory space to users and i want
calculate the total space he used in his folder and to show him/her the total space utilized and total remaining space that can be utilized .
How can I calculate size of entire folder including all files of particular folder in c#.
You can use the following function to calculate the size of specific folder.
Source: https://askgif.com/blog/144/how-can-i-get-the-total-size-of-a-particular-folder-in-c/ (Courtesy: https://askgif.com/)
static String GetDriveSize(String ParticularFolder, String drive)
{
String size = "";
long MaxSpace = 10485760;
String rootfoldersize = #"~/userspace/" + ParticularFolder+ "/";
long totalbytes = 0;
long percentageusage = 0;
totalbytes = GetFolderSize(System.Web.HttpContext.Current.Server.MapPath(rootfoldersize) + "" + drive + "/");
percentageusage = (totalbytes * 100) / MaxSpace;
size = BytesToString(totalbytes);
return size;
}
static long GetFolderSize(string s)
{
string[] fileNames = Directory.GetFiles(s, "*.*");
long size = 0;
// Calculate total size by looping through files in the folder and totalling their sizes
foreach (string name in fileNames)
{
// length of each file.
FileInfo details = new FileInfo(name);
size += details.Length;
}
return size;
}
static String BytesToString(long byteCount)
{
string[] suf = { "B", "KB", "MB", "GB", "TB", "PB", "EB" }; //Longs run out around EB
if (byteCount == 0)
return "0" + suf[0];
long bytes = Math.Abs(byteCount);
int place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)));
double num = Math.Round(bytes / Math.Pow(1024, place), 1);
return (Math.Sign(byteCount) * num).ToString() + suf[place];
}
Hope this will help you.
You can use DirectoryInfo.GetFiles and FileInfo.Length:
DirectoryInfo dir = new DirectoryInfo(#"D:\Data\User_ABC");
FileInfo[] files = dir.GetFiles();
long totalByteSize = files.Sum(f => f.Length);
If you also want to include sub-sirectories:
FileInfo[] files = dir.GetFiles("*.*", SearchOption.AllDirectories);
using System;
using System.IO;
class Program
{
static void Main()
{
Console.WriteLine(GetDirectorySize("C:\\Site\\"));
}
static long GetDirectorySize(string p)
{
// 1.
// Get array of all file names.
string[] a = Directory.GetFiles(p, "*.*");
// 2.
// Calculate total bytes of all files in a loop.
long b = 0;
foreach (string name in a)
{
// 3.
// Use FileInfo to get length of each file.
FileInfo info = new FileInfo(name);
b += info.Length;
}
// 4.
// Return total size
return b;
}
}

How to show HTTP response in Object Choice Field in Blackberry

I am reading a response from server using this code.
public static String getContentString(HttpConnection Connection) throws IOException
{
String Entity=null;
InputStream inputStream;
inputStream = Connection.openInputStream();//May give network io
StringBuffer buf = new StringBuffer();
int c;
while ((c = inputStream.read()) != -1)
{
buf.append((char) c);
}
//Response Formation
try
{
Entity = buf.toString();
return Entity;
}
catch(NullPointerException e)
{
Entity = null;
return Entity;
}
}
I need to show this Entity in object choice field.
For example:
suppose i get response Entity=ThisIsGoingToGood
then, I need to show below way in object choice drop down list.
This
Is
Going
To
Good
Please tell me how to achieve this.
This solution assumes:
The Camel Case format of your strings will always start with an upper case letter.
Only one upper case character in a row is used, even if the word is an acronym. For example, "HTTP response" would be written as "HttpResponse".
public static Vector getContentStrings(HttpConnection connection) throws IOException {
Vector words = new Vector();
InputStream inputStream = connection.openInputStream();
StringBuffer buf = new StringBuffer();
int c;
while ((c = inputStream.read()) != -1)
{
char character = (char)c;
if (CharacterUtilities.isUpperCase(character)) {
// upper case -> new word
if (buf.length() > 0) {
words.addElement(buf.toString());
buf = new StringBuffer();
}
}
buf.append(character);
}
// add the last word
words.addElement(buf.toString());
return words;
}
Then, you'll have a nice Vector full of the choices for your ObjectChoiceField. You can then insert() them, as shown in Signare's answer.
Note: always remember to close your streams, too. I've leave it to you to decide when you're really finished with it, though.
With ref from Nate's Answer- try this -
ObjectListField ol = new ObjectListField(ObjectListField.ELLIPSIS);
ol.setSize(words.size()); //Where words is the vector
for (int i = 0; i < size; i++)
{
ol.insert(i, words.elementAt(i));
}
add(ol);

how to set datarow to String array?

I have a datatable on which I am applying Select() method. After that I want to get the result into an array of String. I have tried the following code but it is not working.
Please let me know the exact solutions for this.
DataTable dtget = HttpContext.Current.Cache["Hello"] as DataTable;
string sqlFilter = "Securityid = '" + CommonClass.Encryptdata(txtSecurity.Text) + "'";
DataRow[] dr = dtget.Select(sqlFilter);
if (dr.Length > 0)
{
String[] Con;
for (int i = 0; i <= dr.Length; i++)
{
dr[i] = dr[i].ToString();
}
}
You have to create the List<T>.
Something like this:
List<String[]> list=new List<String[]>();
if (dr.Length > 0)
{
for (int i = 0; i < dr.Length; i++)
{
string []ar=new string[dtget.Columns.Count];
for(int j=0;j<dtget.Columns.Count;j++)
{
ar[j]=dr[i][j].ToString();
}
list.Add(ar);
}
}
You've declared the array, but not instantiated it. and you're also not writing anything to the actual array, you're trying to write straight back to the datatable.
String[] Con= new String[dtget.Columns.Count];
for (int i = 0; i <= dr.Length; i++)
{
Con[i] = dr[i].ToString();
}
The problem is that you are assigning values to the datarrow in stead of to your string array.
Change
dr[i] = dr[i].ToString();
to
con[i] = dr[i].ToString();
also you are missing the new statement for Con:
Con = new String[dr.Table.Columns.Count];
notice that there is no such thing as dr.Length, you have to check for the column count:
dr.Table.Columns.Count
lastly, you should probably move the string array definition up so it's available outside the IF.
Depending on your needs, what you could do is use the Datarow's ItemArray property. It is an object array in stead of a string array, but before using it's values you can do a "ToString()" and you are all set.
string a = dr.ItemArray[i].ToString();

J2ME TEA Encryption problem in older phones

Hey guys I'm having a huge problem when Encrypting a message in an older phone in comparison with the newer ones.
I've compiled the code to run on older hardware (CLDC1.0, MIDP2.0), and for some reason, when I do a TEA Encryption in a Nokia N70 I end up having one ruined character when it goes from plain-text to TEA. (yes I know, from a lot of chars only that one little char gets ruined...)
When I run exactly the same app on the N8 and other more recent phones however I get it encrypting correctly.
before I post the code however here's a small explanation on what it does:
basically it receives a String and a boolean inputs, the boolean states if it's for encryption or decryption purposes, whilst the string is what I want to encode or decode.
from there, I basically strip the String into a byte array, treat it accordingly (if for encrypt or decrypt) and later turn it into a String, which I then return (decrypt) or I encode in Base64 (encrypt).
The reason to encapsulate in Base64 is so it can be sent by sms, since this encoding uses non-special characters it keeps the sms limit up to 160 characters, which is desirable for the app.
now for the code:
private String HandleTEA(String input, boolean aIsEncryption) throws UnsupportedEncodingException
{
System.out.println(input);
String returnable = "";
try
{
TEAEngine e = new TEAEngine();
if (aIsEncryption)
{
e.init(true, TEAkey);
}
else
{
if(getDebug())
{
input = input.substring(1);
}
input = base64.decodeString(input);
e.init(false, TEAkey);
}
byte[] aData = input.getBytes("ISO-8859-1");
byte[] textToUse = aData;
int len = ((textToUse.length + 16 - 1) / 16) * 16;
byte[] secondUse = new byte[len];
for(int i = 0; i < textToUse.length; i++)
{
secondUse[i] = textToUse[i];
}
for(int i = textToUse.length; i < secondUse.length; i++)
{
secondUse[i] = 0;
}
int blockSize = e.getBlockSize();
byte[] outBytes = new byte[secondUse.length];
for (int chunkPosition = 0; chunkPosition < secondUse.length; chunkPosition += blockSize)
{
int chunkSize = Math.min(blockSize, (textToUse.length - (chunkPosition * blockSize)));
e.processBlock(secondUse, chunkPosition, outBytes, chunkPosition);
}
if(aIsEncryption)
{
Baseless = new String(outBytes, "ISO-8859-1");
String encodedString = base64.encodeString(Baseless);
char[] theChars = new char[encodedString.length()+1];
for(int i = 0; i < theChars.length; i++)
{
if(i == 0)
{
theChars[i] = '1';
}
else
{
theChars[i] = encodedString.charAt(i-1);
}
}
byte[] treating = new byte[theChars.length];
for(int i = 0; i < theChars.length; i++)
{
treating[i] = (byte)theChars[i];
}
returnable = new String(treating, "ISO-8859-1");
}
else
{
char[] theChars = new String(outBytes, "ISO-8859-1").toCharArray();
String fixed ="";
for(int i = 0; i < theChars.length; i++)
{
char c = theChars[i];
if (c > 0) fixed = fixed + c;
}
returnable = fixed;
}
}
catch(Exception e)
{
e.printStackTrace();
}
return returnable;
}
Anyone have any idea on what might be happening?
for comparison this is what I'm getting from the N70:
e+TgV/fU5RUOYocMRfG7vqpQT+jKlujU6eIzZfEjGhXdFwNB46wYNSiUj5H/tWbta26No6wjQylgTexhS6uqyw==
and from the N8:
e+TgV/fU5RUOYocMRfG7vqpQT+jKlujU6eIzZfEjgBXdFwNB46wYNSiUj5H/tWbta26No6wjQylgTexhS6uqyw==
as you can see everything looks similar, but in the middle of the code what gets encoded as Gh on the N70 shows up as gB on the N8...
when decrypting the data encrypted by the N70 we get some really weird chars:
will add this here tomorrow since I don't have the saved output with me
both are using the same key (in real-life tho they'll be using a key that's randomly generated on startup)
here's the key used:
0b1b5e0167aaee06
Hope you can help me out with this and Thanks for your interest and assistance!
your code is hard to understand, but Baseless = new String(outBytes, "ISO-8859-1"); and any similar constructs are almost certainly incorrect. Why do you want to make a String out of cipher? Just base64 encode outBytes directly.

Resources