I have a form that has a list and a button. When you press the button, I want it to write the contents of a specific file(scores.txt) in the list.
This is my code now but with this I can choose the file, but it doesn't open it automatically:
private void btnOpen_Click(object sender, EventArgs e)
{
using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Text Documents(*.txt)|*.txt", ValidateNames = true, Multiselect = false })
{
if (ofd.ShowDialog()==DialogResult.OK)
{
string[] lines = System.IO.File.ReadAllLines(ofd.FileName);
List<string> list = new List<string>();
foreach (string s in lines)
{
list.Add(Convert.ToString(s));
listReadFile.Items.Add(s);
}
}
}
}
Just hard code the filename.
string fileName = #"c:\data\score.txt";
enter code here
string[] lines = System.IO.File.ReadAllLines(fileName);
List<string> list = new List<string>();
foreach (string s in lines)
{
list.Add(Convert.ToString(s));
listReadFile.Items.Add(s);
}
That'll be because you're using an OpenFileDialog.
If you want it to open a file automatically, replace ofd.FileName with the path string of the file you want it to open.
As a side note, I recommend adding this string into your application config, instead of hard-coding it directly.
Related
I want to make a program to able to save every file path which the user selected.
after that do some prosses for each file. for example, convert video file one by one.
Could you tell me why foreach does not work?
private void btnInput_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialogInput = new OpenFileDialog();
openFileDialogInput.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
openFileDialogInput.Filter = "Video Files|*.mp4|TS Files|*.ts";
openFileDialogInput.Multiselect = true;
openFileDialogInput.FilterIndex = 1;
DialogResult result = openFileDialogInput.ShowDialog();
string [] inputPath = openFileDialogInput.FileNames;
foreach (var item in inputPath)
{
item;
}
}
inputPath gets all file paths that the user selected. but I don't know how can I get them, one by one and make some prosses on them.
You Can try this:
private void AddWatermark(string videoFilePath)
{
// Add your logic here to add watermark
}
And in the foreach loop:
foreach (var item in inputPath)
{
AddWatermark(item);
}
I have opened a .CSV file in RichTextBox.I added every line's first word to CombobBox items. I want to edit this a specific word and then save it back to the File.
This is how i open the file to richTextBox1.
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Csv files (.csv)|*.csv";
ofd.Title = "Open a file...";
if (ofd.ShowDialog() == DialogResult.OK)
{
StreamReader sr = new StreamReader(ofd.FileName);
richTextBox1.Text = sr.ReadToEnd();
}
Now i want a Button that finds my comboBox1.Text in richTextBox and replace it with txtbox.Text.
My button looks like this:
private void button1_Click(object sender, EventArgs e)
{
using (TextReader reader = new StringReader(richTextBox1.Text))
{
string str = reader.ReadToEnd();
string cbtxt = comboBox1.Text;
string tbtxt = txtbox.Text;
str = str.Replace(cbtxt, tbtxt);
}
}
I would add the method to the end of this button that would save back the text from richTextBox to my .CSV file but this replace method doesnt replace anything in my richTextBox.
My .CSV file (in richTextBox) looks like this:
somestring,somenumber,somespecialcharacters;
somestring2,somenumber2,somespecialcharacters2;
It has about 50 lines,and my combobox is filled with the first words of every line like: "somestring" "somestring2".
When i click on somestring (then its my combobox.text) then i write "newstring" to my txtbox.text. When i click my button it should find comboBox.text in richtxt and replace it with my txtbox.text.
Any ideas why it doesnt work?
You wrote:
but this replace method doesnt replace anything in my richTextBox.
This is because strings in C# are immutable? Whatever you do to strings, the original string is never changed. The result is always in a new string.
See Why .NET String is immutable?
So although your code changes the value of str, the original str that your richtextbox displays is not changed.
string str = reader.ReadToEnd();
string cbtxt = comboBox1.Text;
string tbtxt = txtbox.Text;
str = str.Replace(cbtxt, tbtxt);
str refers to a new string. RichTextBox1.Text still refers to the original string.
Solution: Assign the new string to the rich text box:
this.RichTextBox1.Text = str;
If you want to save the text in a file you'll have to create a FileWriter that will write the new string (not the changed string, strings can't change!).
Depending on how important it is that you don't lose the old file in case of problems, consider using a tmpfile to write, delete the original and move the tmpfile
In order to replace or delete something using a stream reader, you will need to delete every line and replace it with a new (temporary) file.
var tempFile = Path.GetTempFileName(); //Creates temporary file
List<string> linesToKeep = new List<string>(); //Creates list of all the lines you want to keep (everything but your selection)
using (FileStream fs = new FileStream(path(), FileMode.Open, FileAccess.Read)) //(this opens a new filestream (insert your path to your file there)
{
using (StreamReader sr = new StreamReader(fs)) //here is starts reading your file line by line.
{
while (!sr.EndOfStream) //as long it has not finished reading
{
string currentline = sr.ReadLine().ToString(); //this takes the current line it has been reading
string splitline = currentline; //this is a temporary string because you are going to have to split the lines (i think you have 3 so split in "," and then index the first line (your identifier or name)))
if (splitline.Split(';')[0] != ID) //split the line and add your personal identifier so it knows what to keep and what to delete.
{
linesToKeep.Add(currentline); //adds the line to the temporary file list of line that you want to keep
}
}
}
}
File.WriteAllLines(tempFile, linesToKeep); //writes all the lines you want to keep back into a file
File.Delete(path()); //deletes the old file
File.Move(tempFile, path()); //moves temporary file to old location of the old file.
On second notice, check out this code:
private void btnLoad_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
richTextBox1.LoadFile(ofd.FileName);
}
}
private void btnSave_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
richTextBox1.SaveFile(ofd.FileName);
}
}
I think this is more in line with what you had in mind?
I am creating an application that would load DLLs into a ListBox. It does this by the user pressing a button then the user can open files, and load them into the listview.
So it would look something like this.
The DLL is added in by opening the users files then they add it in themselves and into the ListBox.
My question is. How does I get the exact Path to the MaterialSkin.dll, and put it into a string when someone selected MaterialSkin.dll in the ListBox?
private void materialFlatButton3_Click_1(object sender, EventArgs e) //button used to load the DLL into the ListBox.
{
OpenFileDialog OpenFileDialog1 = new OpenFileDialog();
OpenFileDialog1.Multiselect = true;
OpenFileDialog1.Filter = "DLL Files|*.dll";
OpenFileDialog1.Title = "Select a Dll File";
if (OpenFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// put the selected result in the global variable
fullFileName = new List<String>(OpenFileDialog1.FileNames);
// add just the names to the listbox
foreach (string fileName in fullFileName)
{
listBox2.Items.Add(fileName.Substring(fileName.LastIndexOf(#"\") + 1));
}
}
}
If possible I would adjust your OpenFileDialog1 to grab the path when it grabs the file name. Then, using a dictionary instead of a list you can show display member that is just the .dll name, while the value member can be the dir or the dir / .dll name.
Here's what that might look like in the snippet you posted:
private void materialFlatButton3_Click_1(object sender, EventArgs e)
//button used to load the DLL into the ListBox.
{
OpenFileDialog OpenFileDialog1 = new OpenFileDialog();
OpenFileDialog1.Multiselect = true;
OpenFileDialog1.Filter = "DLL Files|*.dll";
OpenFileDialog1.Title = "Select a Dll File";
if (OpenFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// put the selected result in the global variable
// ~~Using Dictionary instead of list~~
fullFileName = new Dictionary<string, string>(OpenFileDialog1.FileNames);
// Populate Listbox from dictionary.
listBox2.Datasource = fullFileName.ToList();
listBox2.DisplayMember = "Value";
listBox2.ValueMember = "Key";
}
}
This makes the assumption you can change your OpenFileDialog1 object to return a dictionary instead of a list.
Then you'll just use listBox2.SelectedValue to get the dir.
The exact path comes to you from OpenFileDialog1.FileNames...
So store the full path in a Dictionary with the key corresponding to the current index as you're populating the listBox. When they select an item in the listbox, use that to do your dictionary lookup.
Assuming that this is a WinForms app and not WPF, then you have a couple of options.
if the 'fullFileName' variable is a class variable, then when the user selects an item in the ListBox, you can loop through the full DLL paths in the fullFileName variable until you the matching file name.
private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
string curItem = listBox1.SelectedItem.ToString();
foreach( var path in fullFileName)
{
if (System.IO.Path.GetFileName(path).Equals(curItem, StringComparison.OrdinalIgnoreCase))
{
MessageBox.Show("Full path = " + path);
break;
}
}
}
Another option is set the DataSource of the ListBox to a list of objects which contain both the DLL name and the full path.Then use the SelectedItemChanged event (not the SelectedIndexChanged) and the SelectedItem will point to the full path.
public class AssemblyItem
{
public string Name {get;set;}
public string FullPath {get;set;}
}
private void materialFlatButton3_Click_1(object sender, EventArgs e)
{
// Use your existing code to get the selection of DLLs
List<AssemblyItem> items = new List<AssemblyItem>();
foreach (string fileName in fullFileName)
{
items.Add(new AssemblyItem()
{
Name = System.IO.Path.GetFileName(fileName),
FullPath = fileName
};
}
listBox1.DataSource = items;
listBox1.DisplayMember = "Name";
listBox1.ValueMember = "FullPath";
listBox1.BindData();
}
BTW, I would recommend using the methods in System.IO.Path to get the file names from the path instead of using LastIndexOf.
I have a listbox that displays the names of the files that are opened either with a dragDrop functionality or with an OpenFileDialog, the file paths are stored in the List named playlist, and the listbox only displays the names without paths and extensions. When my form closes, the playlist content is saved to a .txt file. When I open again my application, the content in the text file is stored again in the listbox and the playlist. But when I add new files after re-opening the form, I don't know why it leaves a blank line between the last files and the recently added ones.
This is the code I use to WRITE the content of playlist(List) in the txt file:
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if(listBox1.Items.Count > 0)
{
StreamWriter str = new StreamWriter(Application.StartupPath + "/Text.txt");
foreach (String s in playlist)
{
str.WriteLine(s);
}
str.Close();
}
This is the code used to READ the same txt file:
private void Form1_Load(object sender, EventArgs e) //Form Load!!!
{
FileInfo info = new FileInfo(Application.StartupPath + "/Text.txt");
if(info.Exists)
{
if (info.Length > 0)
{
System.IO.StreamReader reader = new System.IO.StreamReader(Application.StartupPath + "/Text.txt"); //StreamREADER
try
{
do
{
string currentRead = reader.ReadLine();
playlist.Add(currentRead);
listBox1.Items.Add(System.IO.Path.GetFileNameWithoutExtension(currentRead));
} while (true);
}
catch (Exception)
{
reader.Close();
listBox1.SelectedIndex = 0;
}
}
else
{
File.Delete(Application.StartupPath + "/Text.txt");
}
}
else
{
return;
}
}
The code used to add files to listbox and playlist:
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Select File(s)";
ofd.Filter = "Audio Files (*.mp3, *.wav, *.wma)|*.mp3|*.wav|*.wma";
ofd.InitialDirectory = "C:/";
ofd.RestoreDirectory = false;
ofd.Multiselect = true;
ofd.ShowDialog();
foreach (string s in ofd.FileNames)
{
listBox1.Items.Add(Path.GetFileNameWithoutExtension(s));
playlist.Add(s);
}
listBox1.SelectedIndex = 0;
This is what I get when I add new files after re-opening my form:
Thanks in advance, I hope StackOverflow community can help me!
First of all: debug your code and you'll find the problem yourself :)
Issue is the use of the WriteLine method. The last line you write should use the Write method instead so that you don't have an empty line at the end. Alternatively and easier to implement is to only add non-empty lines to your playlist such like this:
// ...
do
{
string currentRead = reader.ReadLine();
if (!string.IsNullOrWhiteSpace(currentRead)) // ignore empty lines
{
playlist.Add(currentRead);
listBox1.Items.Add(System.IO.Path.GetFileNameWithoutExtension(currentRead));
}
} while (true);
As a side comment: while (true) and using exception handling is a bad approach to end a loop.
I have tried using:
StreamWriter.WriteLine()
StreamWriter.Write()
File.WriteAllText()
But all of those methods write the textbox text to the file without keeping newlines and such chars. How can I go about doing this?
EDIT:
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog s = new SaveFileDialog();
s.FileName = "new_doc.txt";
s.Filter = "Text File | *.txt";
if (s.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
File.WriteAllText(s.FileName, richTextBox1.Text);
}
}
I am using a multiline RichTextBox to do this.
To expand on tzortzik's answer, if you use StreamWriter and simply access the RichTextBox's Lines property, it will do the work for you:
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog s = new SaveFileDialog();
s.FileName = "new_doc.txt";
s.Filter = "Text File | *.txt";
if (s.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
using (StreamWriter sw = new StreamWriter(s.FileName))
{
foreach (string line in richTextBox1.Lines)
{
sw.WriteLine(line);
}
}
}
}
Maybe this would help. Is from StreamWriter class documentation.
string[] str = String.Split(...);
// Write each directory name to a file.
using (StreamWriter sw = new StreamWriter("CDriveDirs.txt"))
{
foreach (DirectoryInfo dir in cDirs)
{
sw.WriteLine(dir.Name);
}
}
The idea is to get the text from your textbox and then split it after \n char. The result will be an array of strings, each element containing one line.
Later edit:
The problem is that return carriage is missing. If you look with debugger at the code, you will see that your string has only \n at a new line instead of \r\n. If you put this line of code in you function, you will get the results you want:
string tbval = richTextBox1.Text;
tbval = tbval.Replace("\n", "\r\n");
There should be other solutions for this issue, looking better than this but this one has quick results.