Hi guys I have this app that does printing based on items on a listbox.
by commatching those items with that in a directory :\slim\slimyyyy
I want to put an "ERROR CHECKING" that would give me a message that in item
on the listbox is not present in the directory .
For instance if there are 8 items or more is not in the said directory give message with the item thats not in the directory.
Find below is my code ,but my try catch does nothing.Any help is very welcome
Thanks in advance.
{
//var printList = new List();
try
{
var printList = new List();
string dir = #"C:\slim\slimyyyy";
if (Directory.Exists(dir))
{
string[] pdf_specFiles = Directory.GetFiles(dir);
if (pdf_specFiles.Length > 0)
{
foreach (object item in listBox1.Items)
{
foreach (string file in pdf_specFiles)
{
string fileName = Path.GetFileName(file);
if (fileName == item.ToString())
{
printList.Add(Path.GetFullPath(file));
}
}
}
foreach (string file in printList)
{
PrintDocument(file);
System.Threading.Thread.Sleep(10000); // wait 10 second say
Application.DoEvents(); // keep UI responsive if Windows Forms app
}
}
}
}
catch (Exception)
{
MessageBox.Show("You are missing Item(s).", "ERROR");
}
}>
Here's the new solution:
- Please put using System.Linq on top of form
private void Form1_Load(object sender, System.EventArgs e)
{
const string directoryPath = #"C:\slim\slimyyyy";
var printList = new List<string>();
foreach (string item in listBox1.Items)
{
var currentFilePath = Path.Combine(directoryPath, item);
if (File.Exists(currentFilePath))
{
printList.Add(item);
}
}
if (!printList.Any())
{
MessageBox.Show("File doesn't exist");
return;
}
foreach (string file in printList)
{
PrintDocument(file);
// Why you want to wait?? Let it print.
}
}
Related
Below is my code where I am successfully renaming only the files inside a a folder and also crawls inside every subfolders and renames the entire .png files.
I am trying to add a customization where if the file name already got #1 or #5 or any #(number) then i want the conversation to skip that file and go to next file
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderDlg = new FolderBrowserDialog();
//folderDlg.ShowDialog();
if (folderDlg.ShowDialog() != DialogResult.OK)
{
return;
}
// Has different framework dependend implementations
// in order to handle unauthorized access to subfolders
RenameAllPngFiles(folderDlg.SelectedPath);
}
private void RenameAllPngFiles(string directoryPath)
{
RenameCurrentPng(directoryPath);
foreach (var item in GetDirectoryInfos(directoryPath))
{
RenameCurrentPng(item.FullName);
}
}
private void RenameCurrentPng(string directoryPath)
{
int fileNameSuffixCounter = 1;
foreach (string originalFullFileName in Directory.EnumerateFiles(directoryPath, "*.png"))
{
// The new file name without path
var newFileName = $"{System.IO.Path.GetFileNameWithoutExtension(originalFullFileName)}#{fileNameSuffixCounter++}{System.IO.Path.GetExtension(originalFullFileName)}";
FileSystem.RenameFile(originalFullFileName, newFileName);
}
}
private DirectoryInfo[] GetDirectoryInfos(string directoryPath)
{
DirectoryInfo di = new DirectoryInfo(directoryPath);
DirectoryInfo[] directories = di.GetDirectories("*", System.IO.SearchOption.AllDirectories);
return directories;
}
Just use the String.Contains method to check for #.
private void RenameCurrentPng(string directoryPath)
{
int fileNameSuffixCounter = 1;
foreach (string originalFullFileName in Directory.EnumerateFiles(directoryPath, "*.png"))
{
string ShortFileName = System.IO.Path.GetFileNameWithoutExtension(originalFullFileName);
if (!ShortFileName.Contains("#"))
{
// The new file name without path
var newFileName = $"{ShortFileName}#{fileNameSuffixCounter++}{System.IO.Path.GetExtension(originalFullFileName)}";
FileSystem.RenameFile(originalFullFileName, newFileName);
}
}
}
I have below code on my browse button.
How can I write code for inputbox cancel button.
private void btnbrowse_Click(object sender, EventArgs e)
{
String sf_no = Microsoft.VisualBasic.Interaction.InputBox(
"You are uploading File For SF NO. ", "Information", def, -1, -1);
ofd.ShowDialog();
ofd.Multiselect = true;
string[] result = ofd.FileNames;
foreach (string y in result)
{
String path = y.Substring(0, y.LastIndexOf("\\"));
String filename = y.Substring(y.LastIndexOf("\\"));
string[] row = new string[] { sf_no,path, filename };
dataGridView2.Rows.Add(row);
}
}
On Cancellation of InputBox, the return value is an empty string, so your code would be
if (sf_no!="")
{
//ok stuff here, including the showdialog logic as shown below
}
{
//cancel stuff here
}
Since ofd.ShowDialog can also be cancelled your code should be :
if (ofd.ShowDialog()==DialogResult.OK)
{
//do stuff on OK button
}
else
{
//do stuff on Cancel button
}
Either call ofd.Multiselect = true; before calling ShowDialog() or set it on Properties box if you'll always have Multiselect anyway.
Thus, your new code are now :
private void btnbrowse_Click(object sender, EventArgs e)
{
String sf_no = Microsoft.VisualBasic.Interaction.InputBox("You are uploading File For SF NO. ", "Information", def, -1, -1);
if (sf_no!="") //we got the sf_no
{
ofd.Multiselect = true;
if (ofd.ShowDialog()==DialogResult.OK)//user select file(s)
{
string[] result = ofd.FileNames;
foreach (string y in result)
{
String path = System.IO.Path.GetDirectoryName(y);
String filename = System.IO.Path.GetFileName(y);
string[] row = new string[] { sf_no,path, filename };
dataGridView2.Rows.Add(row);
}
}
else
{
//handle what happen if user click cancel while selecting file
}
}
else
{
//handle what happen if user click cancel while entering SF NO
}
}
I'm very new to C#. I'm populating a File Explorer using C#. What i want to do now is implementing the listView1_MouseDoubleClick() method so that when I double-click in a sub folder, the current listView will be cleared then it will display files and folders in that subfolders (like what Windows Explorer does). Here's my code:
private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
{
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].Selected == true)
{
string path = listView1.Items[i].Name;
comboBox1.Text = path;
listView1.Items.Clear();
LoadFilesAndDir(path);
}
}
}
private void LoadFilesAndDir(string address)
{
DirectoryInfo di = new DirectoryInfo(address);
try
{
foreach (FileInfo fi in di.GetFiles())
{
listView1.Items.Add(fi.Name);
}
try
{
foreach (DirectoryInfo listd in di.GetDirectories())
{
listView1.Items.Add(listd.FullName, listd.Name, 0);
}
}
catch (Exception e1)
{
}
}
catch (Exception e1)
{
}
}
But it failed to run. When I debug this error step by step, I found out that after this statement: path = listView1.Items[i].Name; the path variable's value is "". So i guess that the reason which let to the error. But I don't know how to fix that... Could you guys help me with this ? Thanks a lot in advanced !
Make sure that you declare the string 'path' first
string path = "";
Then insert this code:
private void listView1_MouseDoubleClick(object sender, EventArgs e)
{
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].Selected == true)
{
path = Convert.ToString(listView1.Items[i]);
// This replaces the part "List View Item: {"
path = path.Replace("ListViewItem: {", "");
// This replaces the part "}"
path = path.Replace("}", "");
comboBox1.Text = path;
listView1.Items.Clear();
LoadFilesAndDir(path);
}
}
}
The code is a bit long, but it works!
I have a code like this.
IEnumerable<string> imagesFileNames = FindImages(imagesFolder);
foreach(string imageFileName in imagesFileNames)
{
//my code
//IEnumerable<string> imagesFilesNames = FindImages(imagesFolder);
// it doesn't work!!
}
Can i update the IENumerable collection in foreach loop?
Welcome to Stackoverflow. You cannot change the IEnumerable your iterating over in that loop.
It looks like you want to recursively look for files:
IEnumerable<string> imagesFileNames = FindImages(imagesFolder, "*.jpg", true);
private IEnumerable<string> FindImages(string dir, string extension, bool isRecursive)
try
{
foreach (string d in Directory.GetDirectories(dir))
{
try
{
foreach (string f in Directory.GetFiles(d, extension))
{
imagesFileNames.Add(f);
}
if (isRecursive) FindImages(d,extension, true);
}
catch (Exception)
{
}
}
}
Thank you all. I realized that after your comments , that's a bad idea.
And decided to change my method. I solved it with a timer with calling the
images' names in order.
private void timer2_Tick(object sender, EventArgs e)
{
a++;
imageFileName = "IMAGES\DB\"+a+".jpg"
\\\my code
}
I have this and this only saves the last folder used when the user closes the application and re-opens it.
private void btnBrowse_Click(object sender, EventArgs e)
{
Properties.Settings.Default.Reload();
fbFolderBrowser.SelectedPath = AppVars.LastSelectedFolder;
if (fbFolderBrowser.ShowDialog() == DialogResult.OK)
{
Properties.Settings.Default.LastSelectedFolder = fbFolderBrowser.SelectedPath.ToString();
Properties.Settings.Default.Save();
}
}
Every time the user selects a folder, I want to save that path. Then, when he clicks the browse button again, I want the default path to be his last selection.
The above is not working. It only saves the last path selected and goes back to it only if I restart the app. How would I go about saving the last path in the same app session?
You need to reload the settings:
Properties.Settings.Default.Reload();
Note that this only works when not running in Debug mode (AFAIK).
I'm gonna post my code here, because none of the answers I had seen addressed all the issues. This will save the location and re-load the settings for a file Browse dialog (file and folder browse dialogs are slightly different when getting path)... the answers above seem to be for the session only(?). Updated with new method to avoid config settings be lost with an update of clickonce app...
Code:
public class ConfigSettingsDictionary
{
public Dictionary<String, String> ConfigSettings = new Dictionary<String, String>();
}
ConfigSettingsDictionary MyConfigurationSettings = new ConfigSettingsDictionary();
private void SaveConfig()
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\YOUR_APP_NAME_PLUS_UNIQUE_VALUE.config"))
{
foreach (var pair in MyConfigurationSettings.ConfigSettings)
{
sw.WriteLine(pair.Key + "=" + pair.Value);
}
}
}
private void LoadConfig()
{
if (System.IO.File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\YOUR_APP_NAME_PLUS_UNIQUE_VALUE.config"))
{
var settingdata = System.IO.File.ReadAllLines(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\YOUR_APP_NAME_PLUS_UNIQUE_VALUE.config");
for (var i = 0; i < settingdata.Length; i++)
{
var setting = settingdata[i];
var sidx = setting.IndexOf("=");
if (sidx >= 0)
{
var skey = setting.Substring(0, sidx);
var svalue = setting.Substring(sidx + 1);
if (!MyConfigurationSettings.ConfigSettings.ContainsKey(skey))
{
MyConfigurationSettings.ConfigSettings.Add(skey, svalue);
}
}
}
}
}
private void UpdateConfig(Dictionary<String, String> keyvaluepairs)
{
foreach (var pair in keyvaluepairs)
{
if (!MyConfigurationSettings.ConfigSettings.ContainsKey(pair.Key))
{
MyConfigurationSettings.ConfigSettings.Add(pair.Key, pair.Value);
}
else
{
MyConfigurationSettings.ConfigSettings[pair.Key] = pair.Value;
}
}
}
then I use it like this (this saves the folder chosen in a file browse dialog and also the file chosen):
string lastused = "";
if (MyConfigurationSettings.ConfigSettings.ContainsKey("openFileDialog2_last_used"))
{
MyConfigurationSettings.ConfigSettings.TryGetValue("openFileDialog2_last_used", out lastused);
}
if (lastused != "")
{
openFileDialog2.InitialDirectory = lastused;
}
else
{
openFileDialog2.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
}
string filestring = "";
if (template_filename == "")
{
try
{
if (openFileDialog2.ShowDialog() == DialogResult.OK)
{
filestring = openFileDialog2.FileName;
String chosenPath = Path.GetDirectoryName(openFileDialog2.FileName);
Dictionary<String, String> settings_to_save = new Dictionary<String, String>();
settings_to_save.Add("openFileDialog2_last_used", chosenPath);
settings_to_save.Add("openFileDialog2_last_used_template_file", filestring);
UpdateConfig(settings_to_save);
}
else return;
}
catch (Exception ex)
{
MessageBox.Show("There was an error.", "Invalid File", MessageBoxButtons.OK);
return;
}
private void YOURFORMNAME_Load(object sender, EventArgs e)
{
// Load configuration file
LoadConfig();
}
private void YOURFORMNAME_FormClosing(object sender, FormClosingEventArgs e)
{
// Save configuration file
SaveConfig();
}