I'm new to C# and I'm trying to copy and rename an image file(.png). The copying process is working. But the copy should be named "OUTPUT.png" and not use the old name or any parts of it.
Important edit:
The old/original file name is not known, because it is created randomly.
I'd appreciate your help, thoughts, etc.
private void Form1_Load(object sender, EventArgs e)
{
string sourceDir = #"C:\Users\booth\Documents\190604_avee_1.4\Files\Snapshots";
string backupDir = #"C:\Users\booth\Documents\190604_avee_1.4\Files";
try
{
string[] picList = Directory.GetFiles(sourceDir, "*.png");
foreach (string f in picList)
{
string fName = f.Substring(sourceDir.Length + 1);
File.Copy(#"C:\Users\booth\Documents\190604_avee_1.4\Files\Snapshots\*.png", #"C:\Users\booth\Documents\190604_avee_1.4\Files\OUTPUT.png");
}
foreach (string f in picList)
{
File.Delete(f);
}
}
catch (DirectoryNotFoundException dirNotFound)
{
Console.WriteLine(dirNotFound.Message);
}
}
Is it possible that your Copy call should be using the fName var that you create the line before? Trying to copy a wildcard filename when you have a var with the file name in it seems impractical. So something like File.Copy(#"[insert path]\"+fName, ...) should work, right?
Now if your purpose is to copy the .png ones from the corresponding folder to the other folder and then delete the images, this code will do the trick.
using System;
using System.IO;
using System.Windows.Forms;
namespace Udemyvericekme
{
public partial class opera : Form
{
public opera()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string sourceDir = #"C:\Users\Ebubekir\Desktop\resimler\";
string backupDir = #"C:\Users\Ebubekir\Desktop\bekrabackup\";
try
{
string[] picList = Directory.GetFiles(sourceDir, "*.png");
foreach (string f in picList)
{
string fName = f.Substring(sourceDir.Length + 1);
try
{
File.Copy(f, backupDir + fName);
}
catch
{
}
}
foreach (string f in picList)
{
File.Delete(f);
}
}
catch (DirectoryNotFoundException dirNotFound)
{
Console.WriteLine(dirNotFound.Message);
}
}
}
}
You can use this code:
using System;
using System.IO;
using System.Windows.Forms;
namespace Udemyvericekme
{
public partial class opera : Form
{
public opera()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string sourceDir = #"C:\Users\Ebubekir\Desktop\resimler\";
string backupDir = #"C:\Users\Ebubekir\Desktop\bekrabackup\";
try
{
string[] picList = Directory.GetFiles(sourceDir, "*.png");
foreach (string f in picList)
{
string fName = f.Substring(sourceDir.Length + 1);
try
{
File.Copy(f, backupDir + "OUTPUT" + fName);
}
catch
{
}
}
foreach (string f in picList)
{
File.Delete(f);
}
}
catch (DirectoryNotFoundException dirNotFound)
{
Console.WriteLine(dirNotFound.Message);
}
}
}
}
File.Copy(f, backupDir + "OUTPUT" + fName);
You just change it here
Related
I'm making a file explorer app using MVVM pattern in C# WPF. Right now I want to implement watcher events that are responsible for adding, removing and renaming items from treeview. I already have adding, and partially renaming (I think that in this case I have to combine deleting and adding). I'm struggling with deletion.
Deleted files are stil in the treeview. For example, Folder shouldn't exist anymore, because I deleted it.
App window
I would very much appreciate help from You. Here's a code I've written in class DirectoryInfoViewModel
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
namespace ViewModels {
public class DirectoryInfoViewModel : FileSystemInfoViewModel
{
public ObservableCollection<FileSystemInfoViewModel> Items { get; private set; } = new ObservableCollection<FileSystemInfoViewModel>();
public bool Open(string path)
{
bool result = false;
try
{
FileSystemWatcher Watcher = new FileSystemWatcher(path);
Watcher.Created += OnFileCreated;
Watcher.Renamed += OnFileRenamed;
Watcher.Deleted += OnFileDeleted;
//Watcher.Changed += OnFileChanged;
Watcher.Error += Watcher_Error;
Watcher.EnableRaisingEvents = true;
foreach (var dirName in Directory.GetDirectories(path))
{
var dirInfo = new DirectoryInfo(dirName);
DirectoryInfoViewModel itemViewModel = new DirectoryInfoViewModel
{
Model = dirInfo
};
itemViewModel.Open(dirName);
Items.Add(itemViewModel);
}
foreach (var fileName in Directory.GetFiles(path))
{
var fileInfo = new FileInfo(fileName);
FileInfoViewModel itemViewModel = new FileInfoViewModel();
itemViewModel.Model = fileInfo;
Items.Add(itemViewModel);
}
result = true;
}
catch (Exception ex)
{
Exception = ex;
}
return result;
}
public Exception Exception { get; private set; }
private static void Watcher_Error(object sender, ErrorEventArgs e) =>
System.Windows.MessageBox.Show(e.GetException().ToString());
public void OnFileCreated(object sender, FileSystemEventArgs e)
{
System.Windows.Application.Current.Dispatcher.Invoke(() => OnFileCreated(e));
}
private void OnFileCreated(FileSystemEventArgs e)
{
Debug.WriteLine("File Created: " + e.Name);
if (!Items.Any(x => x.Caption == e.Name))
{
var dirInfo = new DirectoryInfo(e.FullPath);
DirectoryInfoViewModel itemViewModel = new DirectoryInfoViewModel();
itemViewModel.Model = dirInfo;
Items.Add(itemViewModel);
}
}
public void OnFileDeleted(object sender, FileSystemEventArgs e)
{
System.Windows.Application.Current.Dispatcher.Invoke(() => OnFileDeleted(e));
}
private void OnFileDeleted(FileSystemEventArgs e)
{
Debug.WriteLine("File Deleted: " + e.Name);
if (Items.Any(x => x.Caption == e.Name))
{
var dirInfo = new DirectoryInfo(e.FullPath);
Debug.WriteLine("File path: " + e.FullPath);
DirectoryInfoViewModel itemViewModel = new DirectoryInfoViewModel();
itemViewModel.Model = dirInfo;
Items.Remove(itemViewModel);
}
}
public void OnFileRenamed(object sender, FileSystemEventArgs e)
{
System.Windows.Application.Current.Dispatcher.Invoke(() => OnFileRenamed(e));
}
private void OnFileRenamed(FileSystemEventArgs e)
{
Debug.WriteLine("File Renamed: " + e.Name);
OnFileDeleted(e);
OnFileCreated(e);
}
} }
In private void OnFileDeleted(FileSystemEventArgs e) you create a new DirectoryInfoViewModel and attempt to remove it from the Items collection. ObservableCollection<T>.Remove(T) removes item based on a reference equality check if T does not provide an alternative equality check.
So you attempt to remove an item from for you Items collection which is not in the collection. If you check the return value of Items.Remove(itemViewModel) you will see that it returns false as no item equal to itemViewModel was found in the collection (see Collection.Remove(T)).
This would fix the problem by finding the item you want to remove and then removing it.
private void OnFileDeleted(FileSystemEventArgs e)
{
if (Items.Any(x => x.Caption == e.Name))
{
var toDelete = Items.Single(x => x.Caption == e.Name);
Items.Remove(toDelete);
}
}
I have the .txt files inside the project's debug folder but the listboxes still won't display any of the data.
I've already missed the due date for this project, I just have a very unhelpful professor and I'd love to learn what I did wrong. Thanks!
The overview of what I'm trying to do here is:
Display delimited data into three listboxes from three text files. When a user clicks on an item in the listbox, one line of additional data (an ID) will be displayed in a textbox underneath that listbox. All three listboxes are shown on the same form and all data is delimited using the same character.
Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace LabDay2Modified
{
struct CustomersNames
{
public string custID;
public string firstName;
public string lastName;
public string accountID;
}
struct AccountNumbers
{
public string acctID;
public string accountType;
public string accountNumber;
public string accountAmt;
}
struct LoanInfo
{
public string loanID;
public string loanYears;
public string loanIntRate;
public string loanAmt;
public string customerID;
public string loanType;
}
public partial class Form1 : Form
{
private List<CustomersNames> customerList = new List<CustomersNames>();
private List<AccountNumbers> accountList = new List<AccountNumbers>();
private List<LoanInfo> loanList = new List<LoanInfo>();
public Form1()
{
InitializeComponent();
}
private void ReadCustFile()
{
try
{
StreamReader inputFile;
string line;
CustomersNames entry = new CustomersNames();
char[] delim = { ',' };
inputFile = File.OpenText("customers.txt");
while (!inputFile.EndOfStream)
{
line = inputFile.ReadLine();
string[] tokens = line.Split(delim);
entry.custID = tokens[0];
entry.firstName = tokens[1];
entry.lastName = tokens[2];
entry.accountID = tokens[3];
customerList.Add(entry);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void ReadAcctFile()
{
try
{
StreamReader inputFile;
string line;
AccountNumbers entry = new AccountNumbers();
char[] delim = { ',' };
inputFile = File.OpenText("accounts.txt");
while (!inputFile.EndOfStream)
{
line = inputFile.ReadLine();
string[] tokens = line.Split(delim);
entry.acctID = tokens[0];
entry.accountNumber = tokens[1];
entry.accountType = tokens[2];
entry.accountAmt = tokens[3];
accountList.Add(entry);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void ReadLoanFile()
{
try
{
StreamReader inputFile;
string line;
LoanInfo entry = new LoanInfo();
char[] delim = { ',' };
inputFile = File.OpenText("loans.txt");
while (!inputFile.EndOfStream)
{
line = inputFile.ReadLine();
string[] tokens = line.Split(delim);
entry.customerID = tokens[0];
entry.loanID = tokens[1];
entry.loanType = tokens[2];
entry.loanYears = tokens[3];
entry.loanIntRate = tokens[4];
entry.loanAmt = tokens[5];
loanList.Add(entry);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void CustInfo()
{
foreach(CustomersNames entry in customerList)
{
customerListBox.Items.Add(entry.custID + " " + entry.firstName + " " + entry.lastName);
}
}
private void AcctInfo()
{
foreach (AccountNumbers entry in accountList)
{
accountListBox.Items.Add(entry.accountNumber + " " + entry.accountType + " " + entry.accountAmt);
}
}
private void LoansInfo()
{
foreach (LoanInfo entry in loanList)
{
loanListBox.Items.Add(entry.loanID + " " + entry.loanType + " " + entry.loanYears+" "+entry.loanIntRate+" "+entry.loanAmt);
}
}
private void exitButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void customerListBox_SelectedIndexChanged(object sender, EventArgs e)
{
int index = customerListBox.SelectedIndex;
customerAccountID.Text = "Account ID: " + customerList[index].accountID;
}
private void loanListBox_SelectedIndexChanged(object sender, EventArgs e)
{
int index = loanListBox.SelectedIndex;
loanCustomerID.Text = "Customer ID: " + loanList[index].customerID;
}
private void accountListBox_SelectedIndexChanged(object sender, EventArgs e)
{
int index = accountListBox.SelectedIndex;
accountAccountID.Text = "Account ID: " + accountList[index].acctID;
}
private void Form1_Load(object sender, EventArgs e)
{
ReadCustFile();
CustInfo();
ReadAcctFile();
AcctInfo();
ReadLoanFile();
LoansInfo();
}
}
}
You can use the following .txt file to see if it works for you.
Then, you will get the following result.
Besides, you can set the similar style for other txt files.
I have a list variable and I created an iterator for it to print out its content. It's working in the console application but when i try to do it using windows form(gui) it doesn't work
PROGRAM.CS
namespace gui
{
static class Program
{
public class studentdata
{
public string id, name, password, academicyear, finishedcourseslist, ipcourseslist;
public int noCoursesF, noCoursesIP;
public List<string> coursesF;
public List<string> coursesIP;
public studentdata()
{
id = "2015123";
password = "Student";
coursesF = new List<string>();
coursesIP = new List<string>();
}
public studentdata(string ID, string NAME, string PASSWORD)
{
id = ID;
}
**public void view_finished_courses()
{
List<string> finished = coursesF;
foreach (string n in finished)
{
finishedcourseslist += n;
}
MessageBox.Show(finishedcourseslist, "Finished courses");
}
public void view_ip_courses()
{
List<string> progress = coursesIP;
foreach (string m in progress)
{
ipcourseslist += m;
}
MessageBox.Show(ipcourseslist, "Finished courses");
}**
}
public class Admin
{
public string name, password;
public Admin()
{
name = "Admin";
password = "Admin";
}
}
//functionssssss
internal static studentdata studentSearch(string IDsearch)
{
FileStream FS = new FileStream("Students.txt", FileMode.Open);
StreamReader SR = new StreamReader(FS);
studentdata std = new studentdata();
while (SR.Peek() != -1)
{
string z = SR.ReadLine();
String[] Fields;
Fields = z.Split(',');
if (IDsearch.CompareTo(Fields[0]) == 0)
{
std.id = Fields[0];
std.password = Fields[1];
std.name = Fields[2];
std.noCoursesF = int.Parse(Fields[3]);
int currentField = 4;
for (int course = 0; course < std.noCoursesF; course++)
{
std.coursesF.Add(Fields[currentField]);
currentField++;
}
std.noCoursesIP = int.Parse(Fields[currentField]);
currentField++;
for (int course = 0; course < std.noCoursesIP; course++)
{
std.coursesIP.Add(Fields[currentField]);
currentField++;
}
std.academicyear = Fields[currentField];
SR.Close();
return std;
}
else continue;
}
SR.Close();
studentdata araf = new studentdata();
return araf;
}
}
FORM.CS
namespace gui
{
public partial class Form3 : Form
{
Program.studentdata student = new Program.studentdata();
public Form3()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button5_Click(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
student.view_finished_courses();
}
private void button6_Click(object sender, EventArgs e)
{
student.view_ip_courses();
}
}
}
The output is an empty message box, I don't know why variable isn't added.
Replace messagebox line with
MessageBox.Show(string.Join(",", coursesF.ToArray()), "Finished courses");
It seems like your code is incomplete. Nowhere in the code which gets executed after you clicked button4 you are adding items to coursesF. It seems that you are adding items in this line: std.coursesF.Add(Fields[currentField]);
This line is in your function studentSearch(IDsearch), the function never gets called.
In this function you got a string z in which all the data of a student is saved (string z = SR.ReadLine()). You must somehow fill this string z. You can use a TextBox in your form and pass the value into the string, use a string from a text file or use the console input(see here: Get input from console into a form).
As you can see the issue is not a one line fix.
I am creating an application where I have a ListBox which has items that are read in from a text file using StreamReader. I have created a search form but I'm not sure what to do next. Can anyone give me some suggestions please? Here is my code:
My code for the ListBox (sorry it's so long)
public partial class frmSwitches : Form
{
public static ArrayList switches = new ArrayList();
public static frmSwitches frmkeepSwitches = null;
public static string inputDataFile = "LeckySafe.txt";
const int numSwitchItems = 6;
public frmSwitches()
{
InitializeComponent();
frmkeepSwitches = this;
}
private void btnDevices_Click(object sender, EventArgs e)
{
frmDevices tempDevices = new frmDevices();
tempDevices.Show();
frmkeepSwitches.Hide();
}
private bool fileOpenForReadOK(string readFile, ref StreamReader dataIn)
{
try
{
dataIn = new StreamReader(readFile);
return true;
}
catch (FileNotFoundException notFound)
{
MessageBox.Show("ERROR Opening file (when reading data in) - File could not be found.\n"
+ notFound.Message);
return false;
}
catch (Exception e)
{
MessageBox.Show("ERROR Opening File (when reading data in) - Operation failed.\n"
+ e.Message);
return false;
}
}
private bool getNextSwitch(StreamReader inNext, string[] nextSwitchData)
{
string nextLine;
int numDataItems = nextSwitchData.Count();
for (int i = 0; i < numDataItems; i++)
{
try
{
nextLine = inNext.ReadLine();
if (nextLine != null)
nextSwitchData[i] = nextLine;
else
{
return false;
}
}
catch (Exception e)
{
MessageBox.Show("ERROR Reading from file.\n" + e.Message);
return false;
}
}
return true;
}
private void readSwitches()
{
StreamReader inSwitches = null;
Switch tempSwitch;
bool anyMoreSwitches = false;
string[] switchData = new string[numSwitchItems];
if (fileOpenForReadOK(inputDataFile, ref inSwitches))
{
anyMoreSwitches = getNextSwitch(inSwitches, switchData);
while (anyMoreSwitches == true)
{
tempSwitch = new Switch(switchData[0], switchData[1], switchData[2], switchData[3], switchData[4], switchData[5]);
switches.Add(tempSwitch);
anyMoreSwitches = getNextSwitch(inSwitches, switchData);
}
}
if (inSwitches != null) inSwitches.Close();
}
public static bool fileOpenForWriteOK(string writeFile, ref StreamWriter dataOut)
{
try
{
dataOut = new StreamWriter(writeFile);
return true;
}
catch (FileNotFoundException notFound)
{
MessageBox.Show("ERROR Opening file (when writing data out)" +
"- File could not be found.\n" + notFound.Message);
return false;
}
catch (Exception e)
{
MessageBox.Show("ERROR Opening File (when writing data out)" +
"- Operation failed.\n" + e.Message);
return false;
}
}
public static void writeSwitches()
{
StreamWriter outputSwitches = null;
if (fileOpenForWriteOK(inputDataFile, ref outputSwitches))
{
foreach (Switch currSwitch in switches)
{
outputSwitches.WriteLine(currSwitch.getSerialNo());
outputSwitches.WriteLine(currSwitch.getType());
outputSwitches.WriteLine(currSwitch.getInsDate());
outputSwitches.WriteLine(currSwitch.getElecTest());
outputSwitches.WriteLine(currSwitch.getPatId());
outputSwitches.WriteLine(currSwitch.getNumDevice());
}
outputSwitches.Close();
}
if (outputSwitches != null) outputSwitches.Close();
}
private void showListOfSwitches()
{
lstSwitch.Items.Clear();
foreach (Switch b in switches)
lstSwitch.Items.Add(b.getSerialNo()
+ b.getType() + b.getInsDate()
+ b.getElecTest() + b.getPatId() + b.getNumDevice());
}
My code for the search form:
private void btnSearch_Click(object sender, EventArgs e)
{
frmSearchSwitch tempSearchSwitch = new frmSearchSwitch();
tempSearchSwitch.Show();
frmkeepSwitches.Hide();
}
If using a List<T> and lambda is not possible for you then go no farther.
Here I use a List<T> for the data source of a ListBox and mocked up data as where the data comes from is not important but here I am focusing on searching on a property within a class where a select is used to index the items then the where searches in this case) for a specific item, if found the index is used to move to the item. No code present for if not located as this is easy for you to do if the code here is something that is doable for you.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace ListBoxSearch_cs
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
var results =
((List<Item>)ListBox1.DataSource)
.Select((data, index) => new
{ Text = data.SerialNumber, Index = index })
.Where((data) => data.Text == "BB1").FirstOrDefault();
if (results != null)
{
ListBox1.SelectedIndex = results.Index;
}
}
private void Form1_Load(object sender, EventArgs e)
{
var items = new List<Item>() {
new Item {Identifier = 1, SerialNumber = "AA1", Type = "A1"},
new Item {Identifier = 2, SerialNumber = "BB1", Type = "A1"},
new Item {Identifier = 3, SerialNumber = "CD12", Type = "XD1"}
};
ListBox1.DisplayMember = "DisplayText";
ListBox1.DataSource = items;
}
}
/// <summary>
/// Should be in it's own class file
/// but done here to keep code together
/// </summary>
public class Item
{
public string SerialNumber { get; set; }
public string Type { get; set; }
public int Identifier { get; set; }
public string DisplayText
{
get
{
return SerialNumber + " " + this.Type;
}
}
}
}
I'm trying to walk through a whole directory tree and print out all the file names on a listbox control. I wrote some code but there are errors. Not sure what I'm doing wrong. By the way, this is in C# using WPF in Visual Studio.
Here is the whole project solution in Visual Studio: http://tinyurl.com/a2r5jv9
Here is the code from MainWindow.xaml.cs if you don't want to download the project solution: http://pastebin.com/cWRTeq3N
I'll paste the code here as well.
public partial class MainWindow : Window
{
private void Button_Click_1(object sender, RoutedEventArgs e)
{
string sourcePath = #"C:\temp\";
static void DirSearch(string sourcePath)
{
try
{
foreach (string d in Directory.GetDirectories(sourcePath))
{
foreach (string f in Directory.GetFiles(d))
{
listBox1.Items.Add(f);
}
DirSearch(d);
}
}
catch (Exception ex)
{
listBox1.Items.Add(ex.Message);
}
}
}
}
There is a complete example on the Microsoft support site
The issue here is that you want to call DirSearch from the event handler, but it appears you're trying to define the method DirSearch inside the event handler. This is not valid.
You need to change your code as follows:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
string sourcePath = #"C:\temp\";
this.DirSearch(sourcePath);
}
private void DirSearch(string sDir)
{
try
{
foreach (string f in Directory.GetFiles(sDir, txtFile.Text))
{
lstFilesFound.Items.Add(f);
}
foreach (string d in Directory.GetDirectories(sDir))
{
this.DirSearch(d);
}
}
catch (System.Exception excpt)
{
listBox1.Items.Add(ex.Message);
}
}
Use GetDirectories() overload accepting SearchOption:
string[] dirs = Directory.GetDirectories(path, "*", SearchOption.AllDirectories))
foreach(dir)
{
...
}
or better EnumerateFiles():
IEnumerable<string> files = Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories))
foreach(files)
{
...
}
Notice it performs lazy filesystem scan.