I've tried and tried but I can't figure out how I'm supposed to fix this.
I have a listView that reads data from a text file.
private void Form3_Load(object sender, EventArgs e)
{
listView1.View = View.Details;
listView1.FullRowSelect = true;
listView1.Columns.Add("Modell", 200);
listView1.Columns.Add("Kw", 100);
listView1.CheckBoxes = true;
string RD_Paneler = "./Data/Paneler.txt";
try
{
List<string> data = File.ReadAllLines(RD_Paneler).ToList();
foreach (string d in data)
{
string[] items = d.Split(new char[] { ',' },
StringSplitOptions.RemoveEmptyEntries);
listView1.Items.Add(new ListViewItem(items));
}
}
catch
{
}
}
`
So then I wanted the user to be able to press a "DELETE" button and all the checkboxed items would be deleted.
private void button2_Click(object sender, EventArgs e)
{
string exeFolder = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
string settingFile = exeFolder + "/Data/Paneler.txt";
var tempFile = Path.GetTempFileName();
string alltext = File.ReadAllText(settingFile);
foreach (ListViewItem item in listView1.Items)
{
var linesToKeep = File.ReadLines(settingFile).Where(l => l != item.Checked.ToString());
if (item.Checked)
{
listView1.Items.Remove(item);
File.WriteAllLines(tempFile, linesToKeep);
File.Delete(settingFile); //Here is where to program crash happends.
File.Move(tempFile, settingFile);
}
}
}
The problem now is that when the program tries to delete the file and replace it with the new one the program crashes because the file it tries to delete is already in use because of the listview.
Here's few solutions -
Use File.ReadAllLines() instead of File.ReadLines(). This should solve the primary problem you are having.
Since you have already read the settingsFile once in memory into alltext. Just use that to iterate over lines like alltext.Split('\n'). Even better IMO.
Hard to understand what your code is doing. Seems sketchy that in a for loop, you have set it up to write, delete, and move the same two files over and again?
Related
I need to read a text file containing time stamps and temperatures. The thing is, I need to only show the temperatures in a listBox, spliting the string before displaying it.
So far I've managed to show the text file in the list, but im struggling with removing the timestamps.
My code:
public partial class Form1 : Form
{
OpenFileDialog openFile = new OpenFileDialog();
string line = "";
private void button1_Click(object sender, EventArgs e)
{
if (openFile.ShowDialog() == DialogResult.OK)
{
StreamReader sr = new StreamReader(openFile.FileName);
while(line != null)
{
line = sr.ReadLine();
if(line != null)
{
string[] newLine = line.Split(' ');
listBox1.Items.Add(newLine);
}
}
sr.Close();
}
}
Now the listBox only shows String[] array.
Oh, and also I need to include this in my code:
const int numOfTemp = 50;
double dailyTemp[numOfTemps];
The textfile is in this format:
11:11:11 -10,50
You should take [1] item of the the array after Split:
using System.Linq;
...
private void button1_Click(object sender, EventArgs e)
{
if (openFile.ShowDialog() != DialogResult.OK)
return;
var temps = File
.ReadLines(openFile.FileName)
.Select(line => line.Split(' ')[1]); // we need temperature only
try {
listBox1.BeginUpdate();
// In case you want to clear previous items
// listBox1.Items.Clear();
foreach (string temp in temps)
listBox1.Items.Add(temp);
}
finally {
listBox1.EndUpdate();
}
}
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'm using the function below to add items to a DataGridView.
void addFiles(List<string> files)
{
foreach (var item in filesFound)
{
if (File.Exists(item))
{
fileList.Add(item);
MessageBox.Show(item);
string p = GetFolderPath(Personal) + #"\Music Database\";
Directory.CreateDirectory(p);
string file="";
try
{
StreamReader read = new StreamReader(p + "musicdatabase.txt");
file = read.ReadToEnd();
read.Close();
}
catch (Exception e)
{
if (e.ToString().Contains(""))
{
//add error code here later
}
}
StreamWriter write = new StreamWriter(p + "musicdatabase.txt");
write.WriteLine(file + item);
write.Close();
dataGridView1.Rows.Add(getTitle(item), getArtist(item), getDuration(item), item);
}
else
{
//add file not found error code here
}
}
}
The function works fine. It adds the details perfectly. getTitle();, getArtist(); and getDuration(); do what they say. They use TagLib# to get the details of audio files. The file path of the audio file gets written to a text file in the users documents.
The problem arises when I load the form: I read the text file as a whole, putting each line into a new index of List<string> textlist = new List<string>();. This is fine. The list has each line. I then run addFiles(textlist);. I launch the program and it loads, but nothing is added to the DataGridView.
I have a feeling it may be to do with the fact it might not be loaded when the Form_Load is triggered.
private void Form1_Load(object sender, EventArgs e)
{
string p = GetFolderPath(Personal) + #"\Music Database\musicdatabase.txt";
//MessageBox.Show(p);
//MessageBox.Show(File.Exists(p).ToString());
if (File.Exists(p))
{
string[] text = File.ReadAllLines(p);
List<string> textlist = new List<string>();
textlist = text.ToList();
// -- THIS PROVES THE textlist LIST CONTAINS ITEMS --
//foreach (var item in textlist)
//{
//MessageBox.Show(item);
//MessageBox.Show(textlist[0]);
//}
//THIS IS THE PROBLEM
addFiles(textlist);
}
}
Your problem is here:
foreach (var item in filesFound)
You are referencing what appears to be a global variable called filesFound,
rather than the variable files that is passed to the function.
I am attempting to save a simple list to a file without using Serialize. Is this possible?
public partial class Form1 : Form
{
public List<string> _testList = new List<string>();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int _add = 0;
string _addString ="";
for (int i = 0; i < 5; i++)
{
_add =+ i;
_addString = Convert.ToString(_add);
_testList.Add(_addString);
}
TextWriter tw = new StreamWriter("SavedList.txt", true);
foreach (string s in _testList)
tw.WriteLine(s);
tw.Close();
StreamReader streamReader = new StreamReader("SavedList.txt");
// Read the data to the end of the stream.
listBox1.Text = streamReader.ReadToEnd();
// Close the text stream reader.
streamReader.Close();
// Close the file stream.
//fileStream.Close();
}
private void button2_Click(object sender, EventArgs e)
{
Close();
}
}
This emits no errors, however it does nothing.
I will use Serialize if necessary, however the suspicion is that is not necessary. Is it?
You can use the File Class to facilitate this.
File.WriteAllLines("SavedList.txt", _testList.ToArray());
To read it back you can then use:
string[] lines = File.ReadAllLines("SavedList.txt");
foreach (string line in lines)
listBox1.Items.Add(line);
your problem is that the Text field of ListBox
doesn't work like that.
change:
listBox1.Text = streamReader.ReadToEnd();
to:
foreach(string s in streamReader.ReadToEnd().Split(new string[]{"\r\n"}))//!!!the end of line characters may differ depending on your system!!!
{
listBox1.Items.Add(s);
}
the Text field holds the currently selected text . it is not for adding items to the list.
I'm not exactly sure what's going on here--I tried to debug but couldn't really come up with any explanation as to why nothing is being written to my datagridview.
Anybody have any idea?
public partial class CleanPathResults : Form
{
public CleanPathResults()
{
InitializeComponent();
}
public void RenameFolder(string folderName)
{
string regPattern = (#"[~#&$!%+{}]+");
string replacement = "";
List<string> normal = new List<string>();
Regex regExPattern = new Regex(regPattern);
dataGridView1.Rows.Clear();
List<string> cleanDirNames = new List<string>();
try
{
if (regExPattern.IsMatch(folderName))
{
string cleanup = regExPattern.Replace(folderName, replacement);
System.IO.Directory.Move(folderName, cleanup);
DataGridViewRow grid = new DataGridViewRow();
grid.CreateCells(dataGridView1);
grid.Cells[0].Value = folderName;
grid.Cells[1].Value = cleanup;
dataGridView1.Rows.Add(grid);
folderName = cleanup;
cleanDirNames.Add(cleanup);
}
else
{
normal.Add(folderName);
}
}
catch(Exception e)
{
throw;
}
DirectoryInfo di = new DirectoryInfo(folderName);
DirectoryInfo[] diArr = di.GetDirectories();
List<string> subdirectories = new List<string>();
try
{
foreach (DirectoryInfo subdir in diArr)
{
subdirectories.Add(subdir.ToString());
}
}
catch(Exception e)
{
throw;
}
try
{
foreach (string folder in subdirectories)
{
string sF = folder;
RenameFolder(folderName + "\\" + sF);
}
}
catch(Exception e)
{
throw;
}
}
private void button1_Click_1(object sender, EventArgs e)
{
Application.Exit();
}
}
I'm not hitting any errors--the app does what it's supposed to do (in this case, make sure folder names do not contain the invalid chars defined in the regex)...however it's just an issue of output not displaying on the dgv.
Any help would be appreciated.
Probably there's no match for your regex... this way no row is being created and added to dataGridView1.
Have you debugged the code? Try to insert a breakpoint within the if statement right after regExPattern.IsMatch. See if the debugger stops there. This way you can assert that a new row is being created.
I'll try to help you more if that holds true.
actually nevermind. figured out that b/c my method keeps calling itself, the datagridview1.Rows.Clear() would clear out everything, everytime the method called itself. Hence no output. Thanks for all your help though Leniel!