ListView of recently opened files - c#

I'm doing a text editor. How do I display a list of the last opened files in the RichTextBox in ListView? You can also click on the ListView string and open the file. Something like the history of opening files. Files are opened using Button (the code below).
private void buttonOpen_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Rich Text Format | *.rtf";
if (ofd.ShowDialog() == DialogResult.OK)
{
richTextBox1.LoadFile(ofd.FileName);
}
else
{
}
}

The easiest way i have done this was store all opened files within a settings string and store all recently opened files within that string with a delimiter like \n(i use this because you cant include it in a fie name so no errors are thrown).
For example, the settings string is stored like this
"C:\my file1\nC:\myFile2\nC:\my file 3"
And when adding a new file to the list
MyApp.Properties.Settings.recents = MyApp.Properties.Settings.recents + "\n" + ofd.FileName;
MyApp.Properties.Settings.Default.Save();
you then split that and use a forloop for each occurance to generate a new listview item like this
string[] recentFiles = MyApp.Properties.Settings.recents.split('\n');
foreach (string recentItem in recentFiles) { MyListView.add(recentItem); }

Related

How to write all textboxes content to text file using streamwritter?

I am a civil engineer who is learning to code (so please don't judge). I am using streamwriter to write textboxes data to txt file but I have hundreds of textboxes. Writing texboxes name one by one is making me crazy and database is not an option. I searched internet for more than 3 hours now but couldn't find the appropriate solution.
The following code works fine but there must be a way to avoid writing all textboxes names. I would really appreciate any guideline here on how to write all textboxes content in text file?.
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
//saveFileDialog1.InitialDirectory = #"C:\";
saveFileDialog1.Title = "Save Project Files";
saveFileDialog1.DefaultExt = "txt";
saveFileDialog1.FileName = "1";
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
string pdfPath = "";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
using(StreamWriter writer = new StreamWriter(saveFileDialog1.FileName))
{
writer.WriteLine(Tb_ProjectName.Text);
writer.WriteLine(tb_ClientName.Text);
writer.WriteLine(tb_ProjectPic.Text);
writer.WriteLine(tb_AgencyName.Text);
writer.WriteLine(tb_AgencyLogo.Text);
writer.WriteLine(tb_ContractorName.Text);
writer.WriteLine(tb_ContractorLogo.Text);
}
pdfPath = saveFileDialog1.FileName;
}
David already gave the correct answer in his comment. So here written out with an additional tip:
In your code, you can iterate over all available text boxes and write their content into a file. There are two thing you have to consider. First, in which order should all textboxes be written. Second, are there any text boxes that should NOT be written into the file.
For both cases you should use the visual editor to set of all text boxes the TabIndex property to set the order in which the content should be written and you can use the property Tag to contain something to mark a text box for not being written into the file.
The code sketch would look something like this:
using(StreamWriter writer = new StreamWriter(saveFileDialog1.FileName))
{
var textBoxesToWrite = this.Controls
.OfType<TextBox>()
.Where(textBox => textBox.Tag != null)
.OrderBy(textBox => textBox.TabIndex)
foreach (var textBox in textBoxesToWrite)
{
writer.WriteLine(textBox.Text);
}
}
1: Create a panel and put all your textboxes in it.
2: Use a foreach loop to get all textboxes from this panel:
string allTextBoxContent = string.Empty;
foreach (var control in panel1.Controls)
{
if (control is TextBox textbox)
{
allTextBoxContent += textbox.Text;
}
}

C# OpenFileDialog/CommonOpenFileDialog

I am working on this piece of code that is supposed to open a file dialog and put them into a textbox.
The error is that every time I select more than 1 file while running the app, I get an error in the textbox. If I select only one file, it works fine.
The code is this
private void filePickerButton_Click(object sender, RoutedEventArgs e)
{
// Create the OpenFileDialog object
OpenFileDialog dialog = new OpenFileDialog();
dialog.InitialDirectory = "C:\\Users";
dialog.Multiselect = true;
// Check to see if we have a result
if (dialog.ShowDialog() == true)
{
filePickerTextBox.Text = dialog.FileNames.ToString();
}
else
{
outputTextBox.Text = "Operation cancelled." + "\n" + outputTextBox.Text;
}
}
I am switching between dialog.Filename.ToString(); (to select one file) and dialog.Filenames.ToString(); to select multiple. When using the latter and selecting a file (whether its only one, or more that one, doesn't matter) the my text box shows System.String[]
Anyone know how to fix this?
Thx!
when you are selecting multiple files you get a array of files, as your textbox says: System.String[]
you could use:
filePickerTextBox.Text = string.join(",", dialog.FileNames);

Why does openfiledialog say 'Path does not exist' or 'Catastrophic Error' after selecting a file for the second time?

I am trying to make a file display. When the user selects a file, it displays the icon of the file in the window. When I select the Google Chrome icon and click on 'OK' in the openfiledialog, the intended result happens. (see pictures below)
However, when I select another icon (e.g Word), it gives me the error 'Path does not exist'.
(see pictures below)
If I select another file (e.g File Explorer) it gives me 'Catastrophic Error' (see pictures below)
For some reason, this problem only happens with shortcut files. For other files like .txt files or .exe files, this problem does not occur.
Here is my code (Add_Item is the name of the button)
private void AddItem_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
if (openFileDialog.ShowDialog() == true)
{
foreach (String myfile in openFileDialog.FileNames)
{
// here myfile represent your selected file name
//get filename
string filename = System.IO.Path.GetFileName(myfile);
//TODO: Create settings
Icon icon1 = System.Drawing.Icon.ExtractAssociatedIcon(myfile);
Bitmap icon = icon1.ToBitmap();
System.Windows.Controls.Image image = new System.Windows.Controls.Image();
image.Source = BitmapToImageSource(icon);
Tiles.Children.Add(image);
}
}
}
Can anyone help me?
Thanks
Alright, {DeferenceLinks = false} fixed my problem.

how to go next line in ListBox?

hey guys i wanna to load a File path in my listBox.
everything is ok
i just have a problem that is when i Close the app and then open it again
loaded files are in the one lane and it recognize them as one item in listBox
i tried to use "\n" , "\r" none of these works...
so what u guys suggest?
(i save user changes in App Setting to read them later)
private void Form1_Load(object sender, EventArgs e)
{
if (Properties.Settings.Default.FileList != string.Empty)
{
fileListBox.Items.Add(Properties.Settings.Default.FileList);
}
UnlockForm f2 = new UnlockForm();
if (Properties.Settings.Default.PasswordCheck == true)
f2.ShowDialog();
else
return;
}
private void button1_Click_1(object sender, EventArgs e)
{
op = new OpenFileDialog();
op.Title = "Select your stuff";
op.Filter = "All files (*.*)|*.*";
if (op.ShowDialog() == DialogResult.OK)
{
fileName = op.FileName;
fileListBox.Items.Add(fileName);
}
Properties.Settings.Default.FileList += fileName+"\n";
Properties.Settings.Default.Save();
}
When creating the property in settings designer:
Set the name to whatever you want, for example Files
Set the type as System.Collections.Specialized.StringCollection
Set the scope as User
If you want to have some default values, use ... in Value cell to edit default value.
Then you can easily set it as DataSource of the ListBox.
listBox1.DataSource = Properties.Settings.Default.Files;
Also to add some values:
Properties.Settings.Default.Files.Add("something");
Properties.Settings.Default.Save();
If you added something to the Files, if you want the ListBox shows the changes, set DataSource to null and then to Files again.
It looks like you have defined your FileList as String in our App Settings. There are two ways you can approach this.
a) Using FileList as Collection.
You can change the Type of FileList to StringCollection in your App Settings. Then, you can add items to your list as follows
fileListBox.Items.AddRange(Properties.Settings.Default.FileList.Cast<string>().ToArray());
b) Using FileList as String.
If you really want to retain Properties.Settings.Default.FileList as string, you would need to split it on the run using your delimiter character (let's say ';')
fileListBox.Items.AddRange(Properties.Settings.Default.FileList.Split(new[] { ';' },StringSplitOptions.RemoveEmptyEntries));
In your case, a collection might be a better approach unless you have specific reasons outside the scope of OP to use string.

C# WinForms App - Debugging Errors using OpenFileDialog, MultiSelect, Logging

Background: I'm developing a WinForms application using C# with an OpenFileDialog and FileBrowserDialog that is supposed to:
Enable selection of multiple xls files.
After selection is made, Display selected xlsx filenames in textbox
Copy the selected files to a separate directory Consolidated
Show results in logging window on the bottom of the winForm App
How do you recommend to fix any of the following Errors in Debugging:
After selecting the files from the FileBrowserDialog, another FileBrowserDialog box comes up
Only 1 of the files selected shows up in the textbox. There's not enough room to display all files b/c the file paths are so long. Would it be possible to just display the filename without the full path? Is there a better way for confirming the MultiSelect worked in a WinForm besides displaying the selected files in a textbox that you recommend?
Hitting the Consolidate button does not copy the selected files to the consolidated directory or display the correct log files.
I get the following in the Logging Window: "Source Files: System.String[]"
Here's my code:
private void sourceFiles_Click(object sender, EventArgs e)
{
Stream myStream;
int i = 0;
OpenFileDialog sourceFilesList = new OpenFileDialog();
this.sourceFileOpenFileDialog.InitialDirectory = "i:\\CommissisionReconciliation\\Review\\";
this.sourceFileOpenFileDialog.Filter = "Excel Files (*.xls;*.xlsx;)|*.xls;*.xlsx;|All Files (*.*)|*.*";
this.sourceFileOpenFileDialog.FilterIndex = 2;
this.sourceFileOpenFileDialog.RestoreDirectory = true;
this.sourceFileOpenFileDialog.Multiselect = true;
this.sourceFileOpenFileDialog.Title = "Please Select Excel Source File(s) for Consolidation";
if (sourceFileOpenFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = sourceFileOpenFileDialog.OpenFile()) != null)
{
using (myStream)
{
Log("Source Files: " + sourceFilesList.FileNames);
}
} // ends if
} // ends try
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
} // ends if (sourceFileOpenFileDialog.ShowDialog() == DialogResult.OK)
} // ends public void sourceFiles_Click
private void consolidateButton_Execute_Click(object sender, EventArgs e)
{
string consolidatedFolder = targetFolderBrowserDialog.SelectedPath;
foreach (String file in sourceFileOpenFileDialog.FileNames)
{
try
{
// Copy each selected xlsx files into the specified TargetFolder
System.IO.File.Copy(sourceFileOpenFileDialog.FileName, consolidatedFolder + #"\" + System.IO.Path.GetFileName(sourceFileOpenFileDialog.FileName));
Log("File" + sourceFileOpenFileDialog.FileName + " has been copied to " + consolidatedFolder + #"\" + System.IO.Path.GetFileName(sourceFileOpenFileDialog.FileName));
}
} // ends foreach loop
} // ends void consolidateButton_Execute_Click
I will give +1 up-votes for any helpful answers!
Thanks for looking!
Update: Updated code w/ a foreach (string FileName in sourceFilesList.FileNames) loop and a listbox control, still having problems w/ filebrowser loading 2x, and the "Source Files: System.String[]" message
Your code snippet doesn't match your question very well, there's no sign of you displaying the FolderBrowserDialog. There is an obvious mistake in the File.Copy() call, you pass sourceFileOpenFileDialog.FileName instead of file.
Check this answer for a way to display path names in a limited amount of space:
using System;
using System.ComponentModel;
using System.Windows.Forms;
class PathLabel : Label
{
[Browsable(false)]
public override bool AutoSize
{
get { return base.AutoSize; }
set { base.AutoSize = false; }
}
protected override void OnPaint(PaintEventArgs e)
{
TextFormatFlags flags = TextFormatFlags.Left | TextFormatFlags.PathEllipsis;
TextRenderer.DrawText(e.Graphics, this.Text, this.Font, this.ClientRectangle, this.ForeColor, flags);
}
}
To get only file name from file path use Path.GetFileName(...).
To check if multiple files were selected, you can just check openFileDialog.FileNames Length property - it's an array.
Fixed Logging Window Message: "Source Files: System.String[]" by adding:
foreach (string FileName in sourceFilesList.FileNames)
{
sourceFilesList.FileNames[i] = FileName;
listBoxSourceFiles.Items.Add(FileName);
Log("Source Files: " + sourceFilesList.FileNames[i]);
i++;
}
// under if ((myStream = sourceFileOpenFileDialog.OpenFile()) != null)
Fixed 2 FileBrowserDialog boxes coming up when Selecting files by:
if ((myStream = sourceFilesList.OpenFile()) != null)
// deleted duplicate line

Categories