I added a RichTextBox control to my form. I want to show the data in an ArrayList in the RichTextBox. How can I do this?
try
{
string filepath = "";
string filename = "";
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "XML files|*.xml";
if (ofd.ShowDialog() == DialogResult.OK)
{
filepath = ofd.FileName;
txtPath.Text = filepath + filename;
XMLParser objxmlparser = new XMLParser();
ArrayList al =objxmlparser.readDataLogXml(txtPath.Text);
}
}
I think as long as objects in the ArrayList are simple data types, you could try
try
{
string filepath = "";
string filename = "";
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "XML files|*.xml";
if (ofd.ShowDialog() == DialogResult.OK)
{
filepath = ofd.FileName;
txtPath.Text = filepath + filename;
XMLParser objxmlparser = new XMLParser();
ArrayList al =objxmlparser.readDataLogXml(txtPath.Text);
for (int i = 0; i < al.Count; i++)
{
yourRichTextBox.Text += string.Format("{0}\r\n", al[i].ToString());
}
}
}
Otherwise, if the objects in the ArrayList are custom objects you created, then you need to override the ToString() method in the custom class that you defined
public class YourCustomClass
{
// Your Custom Fields
// Your Custom Methods
public override string ToString()
{
// Format how you want this object to display information about itself
// The {0}, {1}, etc... are place holders for your custom fields
return string.Format("Put what you want to display here: {0} {1} {2}", customField1, customField2, customField3)
}
}
Related
I was asked to make a file copier that will change the name of a file, by adding "_Copy", but will keep the type of file.
For example:
c:\...mike.jpg
to:
c:\...mike_Copy.jpg
Here is my code:
private void btnChseFile_Click(object sender, EventArgs e)
{
prgrssBar.Minimum = 0;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Which file do you want to copy ?";
DialogResult fc = ofd.ShowDialog();
tbSource.Text = ofd.FileName;
tbDestination.Text = tbSource.Text + "_Copy";
}
You can use the classes System.IO.FileInfo and System.IO.Path to do what it appears you are attempting:
OpenFileDialog od = new OpenFileDialog();
if(od.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
System.IO.FileInfo fi = new System.IO.FileInfo(od.FileName);
string oldFile = fi.FullName;
string newFile = oldFile.Replace(System.IO.Path.GetFileNameWithoutExtension(oldFile),
string.Format("{0}_Copy",
System.IO.Path.GetFileNameWithoutExtension(oldFile)));
MessageBox.Show(newFile);
}
Then you can call the following to perform the copy:
System.IO.File.Copy(oldFile, newFile);
You are appending the _Copy onto the end of the filename and not before the extension. You need to add it before the extension:
string destFileName = $"{Path.GetFileNameWithoutExtension(ofd.FileName)}_Copy{Path.GetExtension(ofd.FileName)}";
Or without C# 6:
string destFileName = String.Format("{0}_Copy{1}",
Path.GetFileNameWithoutExtension(ofd.FileName),
Path.GetExtension(ofd.FileName));
Then to get the full path to the file use:
string fullPath = Path.Combine(Path.GetDirectoryName(ofd.FileName, destFileName));
Then to perform the actual copy just use:
File.Copy(ofd.FileName, fullPath);
I have this code
private void button1_Click(object sender, EventArgs e)
{
Stream myStream;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
openFileDialog1.FilterIndex = 1;
openFileDialog1.Multiselect = true;
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
string strfilename = openFileDialog1.FileName;
string filetext = File.ReadAllText(strfilename);
richTextBox3.Text = filetext; // reads all text into one text box
}
}
}
I'm struggling on how to get each line of the text file to a different text box or possibly store it in an array, can some one help please!
File.ReadAllText will read all of the text in a file.
string filetext = File.ReadAllText("The file path");
If you want to store each line separately in an array, File.ReadAllLines can do that.
string[] lines = File.ReadAllLines("The file path");
Optionally, you can use the following to return a list of strings. You can then either bind the list of strings directly to the control, or you can iterate through each item in the list and add them that way. See below:
public static List<string> GetLines(string filename)
{
List<string> result = new List<string>(); // A list of strings
// Create a stream reader object to read a text file.
using (StreamReader reader = new StreamReader(filename))
{
string line = string.Empty; // Contains a single line returned by the stream reader object.
// While there are lines in the file, read a line into the line variable.
while ((line = reader.ReadLine()) != null)
{
// If the line is not empty, add it to the list.
if (line != string.Empty)
{
result.Add(line);
}
}
}
return result;
}
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.
In my app I used OpenFileDialog to select a file from temp location (%temp%). Now when I again use OpenFileDialog, it opens from some other location. This feature is working fine if any folder other than temp is selected.
Is this a bug or a feature or Technical limitation?
I wrote this code.
public string[] OnOpenFile(string filetype)
{
string strReturn = null;
string[] strFilename = null;
System.Windows.Forms.OpenFileDialog fdlg = new System.Windows.Forms.OpenFileDialog();
fdlg.Title = "Select an Excel file to Upload.";
fdlg.Filter = filetype;
fdlg.RestoreDirectory = true;
if (fdlg.ShowDialog() == DialogResult.OK)
{
strFilename = fdlg.FileNames;
}
return strFilename;
}
You can use InitialDirectory property documented at http://msdn.microsoft.com/en-us/library/system.windows.forms.filedialog.initialdirectory.aspx
in your example:
fdlg.InitialDirectory = Path.GetTempPath();
Running this C# Proram in LinqPad produces wanted result
void Main()
{
OnOpenFile();
OnOpenFile();
OnOpenFile();
}
public string[] OnOpenFile()
{
string strReturn = null;
string[] strFilename = null;
System.Windows.Forms.OpenFileDialog fdlg = new System.Windows.Forms.OpenFileDialog();
fdlg.Title = "Select an Excel file to Upload.";
//fdlg.Filter = filetype;
fdlg.InitialDirectory = Path.GetTempPath();
fdlg.RestoreDirectory = true;
if (fdlg.ShowDialog() == DialogResult.OK)
{
strFilename = fdlg.FileNames;
}
return strFilename;
}
If you comment
fdlg.InitialDirectory = Path.GetTempPath();
you can achieve wanted behavior.
Each time file is selected in folder, that folder in OpenFileDialog opens.
If you press Cancel you have to handle your selected path diffrently - in some string variable, then when you open OpenFileDialog again you set InitialDirectory
I need to get the path of the currently selected File or Folder in Windows Explorer to put the ListView. I do not know how to do hope you can help.Thank you
Update Source
public void GetListFileAndFolderOfWindowsExploer()
{
try
{
string fileName;
ArrayList selected = new ArrayList();
Shell32.Shell shell = new Shell32.Shell();
foreach (SHDocVw.InternetExplorer windows in new SHDocVw.ShellWindows())
{
fileName = Path.GetFileNameWithoutExtension(windows.FullName).ToLower();
if (fileName.ToLowerInvariant() == "explorer")
{
Shell32.FolderItems items = ((Shell32.IShellFolderViewDual2)windows.Document).SelectedItems();
foreach (Shell32.FolderItem item in items)
{
lift = new string[] { item.Name, item.Path };
ListViewItem list = new ListViewItem();
list.Text = item.Name;
list.SubItems.Add(item.Path);
list.UseItemStyleForSubItems = true;
listView1.Items.Add(list);
}
}
}
}
catch (Exception ex)
{
writelog(ex.Message);
}
}
You can use an OpenFileDialog(Home and learn OpenFileDialog).
Hope this link helps.
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "C# Help";
fdlg.InitialDirectory = #"c:\";
fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
fdlg.FilterIndex = 2;
fdlg.RestoreDirectory = true;
if (fdlg.ShowDialog() == DialogResult.OK)
{
string dirName =
System.IO.Path.GetDirectoryName(fdlg.FileName);
string drive =
dirName.Split(System.IO.Path.VolumeSeparatorChar)[0];
MessageBox.Show(dirName);
MessageBox.Show(drive);
}
To in order to get selected items you have to use the following interfaces:
IServiceProvider
IShellBrowser
IFolderView
IShellFolder2
IPersistFolder2
or directly
(IEnumIDList and LPITEMIDLIST) foreach all selected items
This works fine in Windows 10.
Your question seems unclear,Hope you are using OpenFileDialog for selecting files,
If you're looking for the file path:
string path = OpenFileDialog1.FileName; //output = c:\folder\file.txt
If you're looking for the directory path:
string path = Path.GetDirectoryName(OpenFileDialog1.FileName); //output = c:\folder
In general, the System.IO.Path class has a lot of useful features for retrieving and manipulating path information.