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);
}
Related
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?
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.
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 have a simple program that copies files and directories from one place to another. I have it set-up that if there are any exceptions (such as if access to the path is denied) it will create a log file with the error.
I have a button that when pressed, performs the copy action. Everything works fine the first time I press the button and the log file is either created or overwritten with the appropriate error messages.
However, if I press the button a second time, the text file is not overwritten and instead the error messages append. If I close out of my program and run it again, the file is overwritten on the first button press. Any thoughts would be greatly appreciated.
target is a string filepath which I'm getting from a FolderBrowserDialog and taking the selected path and setting it to a textbox. loglist is just a simple List<string> I'm using to store the error messages from any exceptions that occur during the copy process.
public partial class Form1 : Form
{
static List<string> logList = new List<string>();
public Form1()
{
InitializeComponent();
}
private static void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
if (source.FullName.ToLower() == target.FullName.ToLower())
return;
if (Directory.Exists(target.FullName) == false)
{
Directory.CreateDirectory(target.FullName);
}
foreach (FileInfo fi in source.GetFiles())
{
try
{
fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
}
catch (Exception ex)
{
logList.Add(ex.Message);
}
}
foreach (DirectoryInfo diSourceSub in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(diSourceSub.Name);
CopyAll(diSourceSub, nextTargetSubDir);
}
}
private void directoryPickerBtn1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderDialog = new FolderBrowserDialog();
DialogResult folderResult = folderDialog.ShowDialog();
if (folderResult == DialogResult.OK)
{
directoryTextbox1.Text = folderDialog.SelectedPath;
}
}
private void directoryPickerBtn2_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderDialog = new FolderBrowserDialog();
DialogResult folderResult = folderDialog.ShowDialog();
if (folderResult == DialogResult.OK)
{
directoryTextbox2.Text = folderDialog.SelectedPath;
}
}
private void copyBtn_Click(object sender, EventArgs e)
{
string source = (directoryTextbox1.Text);
string target = (directoryTextbox2.Text);
DirectoryInfo dirSource = new DirectoryInfo(source);
DirectoryInfo dirTarget = new DirectoryInfo(target);
try
{
CopyAll(dirSource, dirTarget);
if (logList.Count > 0)
{
using (StreamWriter sw = new StreamWriter(target + #"\log.txt", false))
{
foreach (string error in logList)
{
sw.WriteLine(error);
}
}
}
DialogResult result = MessageBox.Show("Copy Succeeded", "Success");
if (result == DialogResult.OK)
{
string myPath = dirTarget.ToString();
System.Diagnostics.Process prc = new System.Diagnostics.Process();
prc.StartInfo.FileName = myPath;
prc.Start();
}
}
catch (Exception)
{
MessageBox.Show("Copy Failed", "Failed");
}
}
}
}
As #Reza Aghaei pointed out in comments, the problem is that you do not clear the logList.
The file gets created anew every time, but each time you click the Copy button, the loglist still contains the results of the previous copy action.
So you need to clear the list when starting a new copy:
private static void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
logList.Clear();
// ...
From your code it seems that you never clear the logList, this means that it appears the file is being appending because the logList still contains all of the old entries.
You'll need to clear the list between copies if you only want relevant entries to that copy, either before you start copying or after you finish writing the file.
This would be better as a separate method
try
{
CopyAll(dirSource, dirTarget);
SaveLog(target + #"\log.txt");
ClearLog();
//...
}
private void SaveLog(string filename)
{
if (logList.Count > 0)
{
FileStream fs = File.Open(target + #"\log.txt", FileMode.Create);
using (StreamWriter sw = new StreamWriter(fs))
{
foreach (string error in logList)
{
sw.WriteLine(error);
}
}
}
}
I'd like to have a user select a folder with the FolderBrowserDialog and have the files loaded into the ListView.
My intention is to make a little playlist of sorts so I have to modify a couple of properties of the ListView control I'm assuming. What properties should I set on the control?
How can I achive this?
Surely you just need to do the following:
FolderBrowserDialog folderPicker = new FolderBrowserDialog();
if (folderPicker.ShowDialog() == DialogResult.OK)
{
ListView1.Items.Clear();
string[] files = Directory.GetFiles(folderPicker.SelectedPath);
foreach (string file in files)
{
string fileName = Path.GetFileNameWithoutExtension(file);
ListViewItem item = new ListViewItem(fileName);
item.Tag = file;
ListView1.Items.Add(item);
}
}
Then to get the file out again, do the following on a button press or another event:
if (ListView1.SelectedItems.Count > 0)
{
ListViewItem selected = ListView1.SelectedItems[0];
string selectedFilePath = selected.Tag.ToString();
PlayYourFile(selectedFilePath);
}
else
{
// Show a message
}
For best viewing, set your ListView to Details Mode:
ListView1.View = View.Details;
A basic function could look like this:
public void DisplayFolder ( string folderPath )
{
string[ ] files = System.IO.Directory.GetFiles( folderPath );
for ( int x = 0 ; x < files.Length ; x++ )
{
lvFiles.Items.Add( files[x]);
}
}
List item
private void buttonOK_Click_1(object sender, EventArgs e)
{
DirectoryInfo FileNm = new DirectoryInfo(Application.StartupPath);
var filename = FileNm.GetFiles("CONFIG_*.csv");
//Filename CONFIG_123.csv,CONFIG_abc.csv,etc
foreach(FileInfo f in filename)
listViewFileNames.Items.Add(f.ToString());
}