I use:
propItem.Value = System.Text.Encoding.UTF8.GetBytes(textBox1.Text + "\0");
where textBox1.Text contains "MMM", to set the Value and save it in a file (propItem.Value is byte[]), but when I try to read the file I use:
string myString = System.Text.Encoding.UTF8.GetString(propItem.Value);
and get: "M\0M\0M\0\0\0". Could anybody advice how to get the proper string, without '\0'. I have seen all the answers here regarding the similar problems, but none of the answers worked in my case.
Loading the file:
Image img0 = null;
string sourceFile;
private void btnLoad_Click(object sender, EventArgs e)
{
using (var selectFileDialog = new OpenFileDialog())
{
if (selectFileDialog.ShowDialog() == DialogResult.OK)
{
sourceFile = selectFileDialog.FileName;
img0 = Image.FromFile(sourceFile);
PropertyItem[] propItems = img0.PropertyItems;
textBox1.Text = "Nothing in the file.";
foreach (PropertyItem propItem in propItems)
{
if (propItem.Id == 0x9286)
{
string myString = System.Text.Encoding.UTF8.GetString(propItem.Value);
textBox1.Text = myString ;
}
}
}
}
}
It should be:
string myString = System.Text.Encoding.Unicode.GetString(propItem.Value);
Related
This is my program, and it work correctly if i put username and password :
try
{
var url = #"https://mail.google.com/mail/feed/atom";
var User = username;
var Pasw = password;
var encoded = TextToBase64(User + ":" + Pasw);
var myweb = HttpWebRequest.Create(url) as HttpWebRequest;
myweb.Method = "POST";
myweb.ContentLength = 0;
myweb.Headers.Add("Authorization", "Basic " + encoded);
var response = myweb.GetResponse();
var stream = response.GetResponseStream();
textBox1.Text += ("Connection established with" + User + Pasw);
}
catch (Exception ex)
{
textBox1.Text += ("Error connection. Original error: " + ex.Message);
now i want read string of texfile, split them and read username and password like this format: username:password . There is my code at the moment:
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
string file_name = "";
file_name = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + file_name;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (StringReader reader = new StringReader(file_name))
{
// Loop over the lines in the string.
int count = 0;
string line;
while ((line = reader.ReadLine()) != null)
{
string[] data = line.Split(':');
string username = data[0].Trim();
string password = data[1].Trim();
count++;
/* Console.WriteLine("Line {0}: {1}", count, line); */
}
reader.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
You open the file selected by the user, but then try to read from a variable file_name that is not the name of a file but the name of a well kwown folder. Perhaps you want this
try
{
if (openFileDialog1.FileName != string.Empty)
{
using (StreamReader reader = new StreamReader(openFileDialog1.FileName))
{
....
}
}
}
In this same code you use a StringReader, but instead you need a StreamReader to read from a file. StringReader takes the value passed in its constructor and return in the ReadLine call. Then you split the line at the colon but of course this is not the content of your file.
There are other problems in your code. For example, what do you do with the username and password loaded from the line? They are declared as local variables and not used anywhere, so at the next loop they are overwritten and lost.
So, a UserData class could be a possible answer
public class UserData
{
public string UserName {get; set;}
public string Password {get; set;}
}
and declare at the form global level an
List<UserData> data = new List<UserData>
and in your loop
public void button1_Click(object sender, EventArgs e)
{
try
{
if (openFileDialog1.FileName != string.Empty)
{
using (StreamReader reader = new StreamReader(openFileDialog1.FileName))
{
int count = 0;
string line;
while ((line = reader.ReadLine()) != null)
{
UserData d = new UserData();
string[] parts = line.Split(':');
d.UserName = parts[0].Trim();
d.Password = parts[1].Trim();
data.Add(d);
}
// At the loop end you could use the List<UserData> like a normal array
foreach(UserData ud in data)
{
Console.WriteLine("User=" + dd.UserName + " with password=" + dd.Password);
}
}
}
}
}
public void button2_Click(object sender, EventArgs e)
{
try
{
if(data.Count() == 0)
{
MessageBox.Show("Load user info first");
return;
}
var url = #"https://mail.google.com/mail/feed/atom";
var encoded = TextToBase64(data[0].UserName + ":" + data[0].Password);
.....
A warning note. Of course this is just demo code. Remember that in a real scenario saving passwords in clear text is a big security concern. The impact of this is relative to the context of your application but should not be downplayed. A better course of action is to store an hashing of the password values and apply the same hashing function when you need to compare password
You are creating StringReader from file_name varialbe, which is (according to your code)
string file_name = "";
file_name = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + file_name;
and points to nothere.
Also you have stream created for file being selected with open file dialog but you haven't use this stream.
I have a program that I need to have a config file with value to be
displayed in my program. Inside my text file I have Wireless = 1
& Cradle = 2.
In my program I will have a label populate the release number only and not the other
characters.
private string searchFile(String path, String searchText)
{
string regex=#"(?i)(?<="+searchText+#"\s*=\s*)\d+";
return Regex.Match(File.ReadAllText(path),regex).Value;//version number
}
This is what I tried and it gives the correct output
string s="Wireless = 1 Cradle = 2";
Regex.Match(s,#"(?i)(?<=Wireless\s*=\s*)\d+").Value;//1
public static string match;
public static string ReadAllText(string path)
{
using (var r = new System.IO.StreamReader(path))
{
return r.ReadToEnd();
}
}
private string Wireless(String path, String searchText)
{
string regex = #"(?i)(?<=" + searchText + #"\s*=\s*)\d+";
match = Regex.Match(ReadAllText(path), regex).Value;
label1.Text = match;
return match;
}
private string Cradle(String path, String searchText)
{
string regex = #"(?i)(?<=" + searchText + #"\s*=\s*)\d+";
match = Regex.Match(ReadAllText(path), regex).Value;
label2.Text = match;
return match;
}
private void button1_Click(object sender, EventArgs e)
{
Wireless(#"\Storage Card\changelog.txt","Wireless");
Cradle(#"\Storage Card\changelog.txt", "Cradle");
}
I am trying to develop upload file function with security as my programming instructor asked me to do. I implemented it in such a way that it will check the size, file format and the existence of the file. The logic was working well except for checking the existence of the file. For example, when I tried to upload a file which is already existed, I will not get a message telling me that the file is already existed and I don't know why it is not working.
protected void UploadFile(object sender, EventArgs e)
{
if(FileUpload1.HasFile)
try
{
string[] validTypes = { "bmp", "gif"};
string ext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
if (size < limit)
{
for (int i = 0; i < validTypes.Length; i++)
{
if (ext == "." + validTypes[i])
{
string path = #"~\Images\";
string comPath = Server.MapPath(path + "\\" + FileUpload1.FileName);
if (!File.Exists(comPath))
{
FileUpload1.PostedFile.SaveAs(comPath);
Label1.Text = "File uploaded";
}
else
{
Label1.Text = "Existed";
}
}
else
{
Label1.Text = "Invalid File." + string.Join(",", validTypes);
}
}
}
else
{
Label2.ForeColor = System.Drawing.Color.Red;
Label2.Text = "file is heavy";
}
}
catch (Exception ex)
{
Label2.Text = "The file could not be uploaded. The following error occured: " + ex.Message;
}
}
When I debugged the code, I found that it will execute the else statement, but instead of displaying it to the user, it will display the message in the outer else statement which is "Invalid File.". Why?
if (ext == "." + validTypes[i])
{
string path = #"~\Images\";
string comPath = Server.MapPath(path + "\\" + FileUpload1.FileName);
if (!File.Exists(comPath))
{
FileUpload1.PostedFile.SaveAs(comPath);
Label1.Text = "File uploaded";
}
else
{
Label1.Text = "Existed";
}
}
else
{
Label1.Text = "Invalid File." + string.Join(",", validTypes);
}
Also, my instructor told me that the following line causes a vulnerability called path traversal.
string path = #"~\Images\";
So how to prevent this security hole? ?Any ideas?
There is logical problem in you code.In the block
for (int i = 0; i < validTypes.Length; i++)
It will always run two time for each file.
What you can do you take a Boolean variable at set it to false.
Go inside the loop and if file found set boolean to true and use break statement.
At the end of loop check for the Boolean value and code accordingly.
Edit-1
Rather than looping through the array you can use like this
string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
int pos = Array.IndexOf(stringArray, value);
if (pos >- 1)
{
// the array contains the string and the pos variable
// will have its position in the array
}
In your case
string[] validTypes = { "bmp", "gif"};
string ext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
int pos = Array.IndexOf(validTypes , ext );
if(pos>=0)
{
string path = #"~\Images\";
string comPath = Server.MapPath(path + "\\" + FileUpload1.FileName);
if (!File.Exists(comPath))
{
FileUpload1.PostedFile.SaveAs(comPath);
Label1.Text = "File uploaded";
}
else
{
Label1.Text = "Existed";
}
}
else
{
Label1.Text = "Invalid File." + string.Join(",", validTypes);
}
I'm a newbie, so I'm sure this is something really basic that I'm missing.
I have a simple program to run through a csv file that contains links to images to save those images in the specified save file location.
I am parsing the cell that contains the url into a List<string[]>.
If I put GetImage(#"http://www.example.com/picture.jpg", 1) my GetImage function performs as it should. When I try to use the loop and pass in the str[0] variable, I receive an error about illegal characters in path.
I've used a MessageBox to tell me what the difference is and as far as I can tell, when I pass the str[0] into the function it adds double quotes(i.e., "http://www.example.com" is displayed instead of http://www.example.com as it is when I just send the one string.
What am I doing wrong?
private void button2_Click(object sender, EventArgs e)
{
string fileName = textBox1.Text;
folderBrowserDialog1.ShowDialog();
string saveLocation = folderBrowserDialog1.SelectedPath;
textBox2.Text = saveLocation;
List<string[]> file = parseCSV(fileName);
int count = 0;
foreach (string[] str in file)
{
if (count != 0)
{
GetImage(str[0], str[4]);
}
count++;
}
//GetImage(#"http://www.example.com/picture.jpg", "1");
}
private void GetImage(string url, string prodID)
{
string saveLocation = textBox2.Text + #"\";;
saveLocation += prodID + ".jpg";
WebClient webClt = new WebClient();
webClt.DownloadFile(url, saveLocation);
}
No matter which function or method creates these quotes, you could replace them all.
String myUrl = str[0];
myUrl = myUrl.Replace("\"", "");
GetImage(myUrl, str[4]);
I think your files contains the quotes or the parseCSV method creates them.
Update:
I used this code and it works with no problem at all and without quotes:
static void Main(string[] args)
{
string fileName = "Test";
//folderBrowserDialog1.ShowDialog();
string saveLocation = ".\\";
//textBox2.Text = saveLocation;
List<string[]> file = new List<string[]>
{
new string[] { "http://www.example.com", "1", "1", "1", "1"},
new string[] { "http://www.example.com", "2", "2", "2", "2"},
};
int count = 0;
foreach (string[] str in file)
{
if (count != 0)
{
GetImage(str[0], str[4]);
}
count++;
}
//GetImage(#"http://www.example.com/picture.jpg", "1");
}
private static void GetImage(string url, string prodID)
{
string saveLocation = ".\\"; // textBox2.Text + #"\"; ;
saveLocation += prodID + ".jpg";
WebClient webClt = new WebClient();
Console.WriteLine(url);
webClt.DownloadFile(url, saveLocation);
}
Hi all i have main form with a treeview control with a set of files displayed under each node. If i had my mouse over that node i will read the values that are present in the text file by using the following code
private void treeViewACH_NodeMouseHover(object sender, TreeNodeMouseHoverEventArgs e)
{
string strFile = string.Empty;
System.Text.StringBuilder messageBoxCS = new System.Text.StringBuilder();
messageBoxCS.AppendFormat(" {0}", e.Node);
strFile = messageBoxCS.ToString().Substring(11);
strFilePath = Directory.GetCurrentDirectory();
strFilePath = Directory.GetParent(strFilePath).ToString();
strFilePath = Directory.GetParent(strFilePath).ToString();
strFilePath = strFilePath + "\\ACH" + "\\" + strFile;
if ((File.Exists(strFilePath)))
{
StreamReader sr = new StreamReader(strFilePath);
StringComparison compareType = StringComparison.InvariantCultureIgnoreCase;
string fileName = Path.GetFileNameWithoutExtension(strFilePath);
string extension = Path.GetExtension(strFilePath);
if (fileName.StartsWith("FileHeader", compareType)
&& extension.Equals(".txt", compareType))
{
string s = sr.ReadToEnd();
StringBuilder sb = new StringBuilder();
//sb.Append("RecordTypeCode\tPriorityCode");
//sb.Append("\n");
//sb.Append("--------------------------------------------------");
//sb.Append("\n");
objFile.ReferenceTypeCode = s.Substring(0, 1);
sb.Append(objFile.ReferenceTypeCode);
string PriorCode = s.Substring(1, 2);
sb.Append(PriorCode);
objFile.getValues(sb.ToString());
frmTemp frmtemp = new frmTemp();
frmtemp.Show();
}
}
Now i would like to place the values in each textboxes on the form load. But as it is a different form i can not access the values from the business layer
I have coded like this on form load
BL.FileHeader objFile = new FileHeader();
private void frmTemp_Load(object sender, EventArgs e)
{
textBox1.Text = objFile.ReferenceTypeCode;
}
But i am unable to display the values any help please..
Add a property to your frmTemp class for each value that you want to display. In your NodeMouseHover handler, assign values to those properties right after you create the instance of the form. Then, in the frmTemp_Load handler, assign the values of those properties to the TextBox controls.
Got the answer by the following
frmTemp frmtmp = new frmTemp(strFileHeader);
frmtmp.Show();
public frmTemp(string str)
{
InitializeComponent();
if (str.StartsWith("1"))
{
this.textBox1.Text = str.Substring(0, 1);
}
else if (str.StartsWith("5"))
{
this.textBox1.Text = str.Substring(0, 1);
this.textBox2.Text = str.Substring(4, 16);
}
}