CommonOpenFileDialog cicon = new CommonOpenFileDialog();
cicon.IsFolderPicker = false;
cicon.Title = "Choose Icon";
cicon.Filters.Add(new CommonFileDialogFilter("Executable Files", "*.exe"));
cicon.Filters.Add(new CommonFileDialogFilter("Icon Files", "*.ico*"));
if (cicon.ShowDialog() == CommonFileDialogResult.Ok)
{
try
{
Image fico = System.Drawing.Icon.ExtractAssociatedIcon(cicon.FileName).ToBitmap();
metroTextBox1.Icon = fico;
}
catch (Exception re)
{
winmsg msg = new winmsg();
msg.Title = "Icon Error - Cannot find any Icon";
msg.Content = "Path: " + re.Message;
msg.ShowDialog();
msg.Dispose();
}
}
else
{
return;
}
I am getting Open file dialog after file chosen, What could be the issue? Above code for click on CustomButton in Metrotextbox.
Related
I'm trying to make a program that loads a configuration file from another application.
If the file exists, it loads it and displays a message, but if the configuration file is not valid, it displays an error message and then opens a dialog box to load the correct file. But if the user reloads the wrong file, the same dialog box should appear again but that's when my code fails.
Similarly, if the file did not exist from the beginning, it displays a dialog box to load the file, but if it is given to cancel the dialog box or an incorrect file is selected again, my code fails.
I know that the solution would be to use loops but I'm not sure how to structure it.
Pd: searchfile() is my function to open dialog box and readconfig() is my function to read config file of another application.
strfilenamepath = #"C:\Users\test\dogs.exe.config";
if (File.Exists(strfilenamepath))
{
onlyFilename = System.IO.Path.GetFileName(strfilenamepath);
textBox1.Text = onlyFilename;
try
{
string[] valores = readConfig(strfilenamepath);
MessageBox.Show(valores[0] + valores[1] + valores[2]);
}
catch (Exception ex)
{
MessageBox.Show("Error loading config file." + ex.Message);
searchFile();
onlyFilename = System.IO.Path.GetFileName(strfilenamepath);
textBox1.Text = onlyFilename;
string[] valores = readConfig(strfilenamepath);
MessageBox.Show(valores[0] + valores[1] + valores[2]);
}
}
else
{
searchFile();
onlyFilename = System.IO.Path.GetFileName(strfilenamepath);
textBox1.Text = onlyFilename;
try
{
readConfig(strfilenamepath);
string[] valores = readConfig(strfilenamepath);
MessageBox.Show(valores[0] + valores[1] + valores[2]);
}
catch (Exception ex)
{
MessageBox.Show("Error loading config file." + ex.Message);
searchFile();
onlyFilename = System.IO.Path.GetFileName(strfilenamepath);
textBox1.Text = onlyFilename;
string[] valores = readConfig(strfilenamepath);
MessageBox.Show(valores[0] + valores[1] + valores[2]);
}
}
It is easier to design it if you extract the reading logic to another method that handles exceptions and returns a Boolean to signal the success and the computed result. The TryDoSomething pattern does exactly this.
In pseudo code
public bool TryReadConfig(string path, out string[] valores)
{
valores = null;
try {
valores = read the values;
return true;
} catch {
Display message;
return false;
}
}
The main loop in pseudo code
strfilenamepath = #"C:\Users\test\dogs.exe.config";
while (true) {
if (File.Exists(strfilenamepath) && TryReadConfig(strfilenamepath, out var valores)) {
Do something with the valores;
break;
}
var ofd = new OpenFileDialog{ ... };
if (ofd.ShowDialog() == DialogResult.OK) {
strfilenamepath = ofd.Filename;
} else {
break; // The user canceled the operation.
}
}
You can do something like this:
try
{
//Code to try open the file to memory
}
catch (Exception ex)
{
while (true)
{
MessageBox.Show(#"Select an valid file");
var path = searchFile();
if (string.IsNullOrWhiteSpace(path))
continue;
try
{
//Code to try open the file to memory
}
catch (Exception ex2)
{
MessageBox.Show(#"The selected file is not valid");
continue;
}
break;
}
}
I want to create a Windows Folder the name of the folder will get it from a TextBox.Text that the user will fill in, but inside this folder it should also create automatically an app.config
This is what I got so far:
private void CreateNewCustomer()
{
Directory.CreateDirectory(#"C:\Users\khaab\Documents\visual studio 2015\Projects\ReadingXML\ReadingXML\bin\Debug\Customers\" + CustomerTextBox.Text);
StreamWriter File = new StreamWriter(#"C:\Users\k.abdulrazak\Documents\visual studio 2015\Projects\ReadingXML\ReadingXML\bin\Debug\Customers\app.config");
File.Close();
MessageBox.Show("You have successfully added a customer", "Customer added", MessageBoxButtons.OK);
}
How can I do that?
You should have a variable that holds the root path whether to create the new folder and the app.config file, e.g., string root = Environment.CurrentDirectory. Then the CreateNewCustomer method would look like:
public void CreateNewCustomer()
{
var di = Directory.CreateDirectory(Path.Combine(root, CustomerTextBox.Text));
if (di.Exists)
{
var fs = File.Create(Path.Combine(di.FullName, "app.config"));
fs.Close();
MessageBox.Show("You have successfully added a customer", "Customer added", MessageBoxButtons.OK);
}
}
How about this:
public void SubmitButton_Click(object sender, EventArgs args)
{
var name = CustomerTextBox.Text
if (String.IsNullOrWhiteSpace(name))
{
MessageBox.Show("Enter a customer name!");
return;
}
var result = CreateNewCustomer(name);
if (result)
{
MessageBox.Show("You have successfully added a customer", "Customer added", MessageBoxButtons.OK);
}
else
{
MessageBox.Show("Something went wrong.", "Customer add failed", MessageBoxButtons.OK);
}
}
private bool CreateNewCustomer(string customerName)
{
var result = true;
try
{
var basepath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Customers");
var custPath = System.IO.Path.Combine(basepath, customerName);
var appconfigpath = System.IO.Path.Combine(custPath, "app.config");
if (!System.IO.Directory.Exists(custPath))
{
System.IO.Directory.CreateDirectory(custPath);
}
System.IO.File.Create(appconfigpath);
}
catch (Exception ex)
{
System.Diagnostics.Trace.TraceError("Error creating customer folder: {0}", ex);
result = false;
}
return result;
}
It seems like my file system watcher is firing mulitple events and then ending up giving me an error:
The process cannot access the file, file is in use.
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
// Form2 popup = new Form2();
if (Directory.Exists(this.textBox2.Text) && string.IsNullOrWhiteSpace(textBox2.Text))
{
MessageBox.Show("Please Select Source Folder");
return;
}
else if (Directory.Exists(this.textBox3.Text) && string.IsNullOrWhiteSpace(textBox3.Text))
{
MessageBox.Show("Please Select Destination Folder");
return;
}
else WatchFile();
private void WatchFile(/*string watch_folder*/)
{
FileSystemWatcher _watcher = new FileSystemWatcher();
_watcher.Path = textBox2.Text;
_watcher.NotifyFilter = NotifyFilters.LastWrite;
_watcher.Filter = "*.log";
_watcher.Changed += new FileSystemEventHandler(InitList);
_watcher.EnableRaisingEvents = true;
_watcher.IncludeSubdirectories = false;
listBox1.Items.Add("Started Monitoring Directory " + textBox2.Text);
listBox1.SelectedIndex = listBox1.Items.Count - 1;
}
private object lockObject = new Object();
public void InitList(object source, FileSystemEventArgs f)
{
_recordList = new List<MyData>();
string fileName = f.FullPath;
string filePath = f.Name;
string trPath = fileName;
string[] arrstringPath = new string[3];
arrstringPath[0] = filePath.Substring(2, 2);
arrstringPath[1] = filePath.Substring(4, 2);
arrstringPath[2] = filePath.Substring(6, 2);
string tempPath = "LG" + arrstringPath[0] + arrstringPath[1] + arrstringPath[2] + ".001";
string v15nativePath = textBox3.Text + tempPath;
_watcher.EnableRaisingEvents = false;
if (!Monitor.TryEnter(lockObject))
{
return;
}
else
try
{
//_watcher.EnableRaisingEvents = false;
_watcher.Changed -= new FileSystemEventHandler(InitList);
FileStream trFS = new FileStream(trPath, FileMode.Open, FileAccess.Read);
StreamReader trSR = new StreamReader(trFS);
// FileStream v15FS = new FileStream(v15nativePath, FileMode.Open, FileAccess.Write);
StreamWriter v15SR = new StreamWriter(v15nativePath, false);
var timeIndex = "S";
Func<string, MyData> values = new Func<string, MyData>(
(x) =>
{
if ((x[0].ToString()) == "S")
{
var temptime = x.IndexOf("S");
timeIndex = x.Substring(temptime + 1, 4);
}
if ((x[0].ToString()) == "C")
{
var trackIndex = x.IndexOf(":");
var titleidString = x.Substring(11, 6);
var trackString = x.Substring(17, 40);
var trackDuration = x.Substring(57, 5);
return new MyData { Time = timeIndex, Duration = trackDuration, TitleID = titleidString, Track = trackString };
}
else
return null;
});
while (trSR.Peek() != -1)
{
var data = trSR.ReadLine();
MyData my = values(data);
if (my != null)
_recordList.Add(my);
}
trFS.Close();
trSR.Close();
var groupData = from data in _recordList
select new
{
Name = data.Track,
Duration = data.Duration,
Time = data.Time,
ID = data.TitleID
};
foreach (var item in groupData)
{
var newstringLen = item.Name.Truncate(27);
var v15timeString = item.Duration;
var v15fileString = "C" + item.Time + ":" + "00" + item.ID + " " + newstringLen + v15timeString;
v15SR.WriteLine(v15fileString);
v15SR.Flush();
}
v15SR.Close();
this.Invoke((MethodInvoker)delegate { listBox1.Items.Add(string.Format("File is Translated")); });
_watcher.Changed += new FileSystemEventHandler(InitList);
}
catch (Exception e)
{
//listBox1.Items.Add("The process failed: "+" "+e.ToString());.
MessageBox.Show("The Process Failed:" + e.ToString());
}
finally
{
Monitor.Exit(lockObject);
_watcher.Path = textBox2.Text;
_watcher.EnableRaisingEvents = true;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
}
I have called _watcher.EnableRaisingEvents = false; before the try block and then make it true in the final block yet. the watching get's disabled while I do the processing then why does it run the InitList method again after it finishes. This seems like a mulitple run on the same file, and so causing this exception
I have the app below. I modified it slightly for easier testing for readers here. I notice that when I set the Filename with an extension, e.g. test.txt, the txt extension is removed by the dialog. However I want users to be able to specify an extension, and more importantly I want to be able to set the extension. One way to hack it in I figure is to modify the filter based on the extension I have. Is this the only way?
I am using VS 2010 Express.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Globalization;
using System.IO;
using System.Windows;
namespace SpeedDating
{
partial class Program
{
[STAThread]
static void Main(string[] args)
{
Form form = new Form();
form.WindowState = FormWindowState.Minimized;
form.ShowInTaskbar = false;
form.TopMost = true;
form.Show();
string filename = "test.txt";
string ext = filename.Substring(filename.LastIndexOf('.'));
SaveFileDialog dialog = new SaveFileDialog();
dialog.Title = "SpeedDating App";
dialog.RestoreDirectory = true;
dialog.CheckFileExists = false;
dialog.CheckPathExists = false;
dialog.SupportMultiDottedExtensions = true;
dialog.AddExtension = false;
dialog.Filter = "All files (*.*)|*.*";
dialog.FileName = DateTime.Now.ToString("yyyyMMdd") + ext;
DialogResult result = dialog.ShowDialog();
if (result == DialogResult.OK && dialog.FileName != "")
{
try
{
FileStream outfs = File.Create(dialog.FileName);
FileStream infs = File.Open(filename, FileMode.Open);
infs.CopyTo(outfs);
infs.Close();
outfs.Close();
MessageBox.Show(form, "Copied file.");
}
catch (NotSupportedException ex)
{
MessageBox.Show(form, "Probably removed the original file.");
}
}
else if (result != DialogResult.Cancel)
{
MessageBox.Show(form, "No path found to write to.");
}
form.Close();
}
}
}
and more importantly I want to be able to set the extension
You can set the .DefaultExt(), .AddExtension(), .Filter(), and .FilterIndex() properties:
string filename = "test.xyz";
SaveFileDialog dialog = new SaveFileDialog();
dialog.Title = "SpeedDating App";
dialog.RestoreDirectory = true;
dialog.CheckFileExists = false;
dialog.CheckPathExists = false;
dialog.SupportMultiDottedExtensions = true;
dialog.Filter = "All files (*.*)|*.*";
dialog.DefaultExt = System.IO.Path.GetExtension(filename);
if (dialog.DefaultExt.Length > 0)
{
dialog.AddExtension = true;
dialog.Filter = dialog.DefaultExt + " files (*." + dialog.DefaultExt + ")|*." + dialog.DefaultExt + "|" + dialog.Filter;
dialog.FilterIndex = 0;
}
dialog.FileName = DateTime.Now.ToString("yyyyMMdd");
DialogResult result = dialog.ShowDialog();
if (result == DialogResult.OK && dialog.FileName != "")
{
Console.WriteLine(dialog.FileName);
}
*Note that if the option to display "File Extensions" is turned OFF in File Explorer, then the dialog will also hide the extension...BUT the above setup will add the set extension to the .FileName() value returned by the dialog.
I'm trying to print a PDF file using Process object. And up to certain extent I could print it successfully. But now I want to set printer properties.. like no of copies, Paper size etc. But I don't see any property to set these values.
I'm using following code to print PDFs
string fileName = "";
string arguments = "";
string verbToUse = "";
int i = 0;
ProcessStartInfo startInfo = new ProcessStartInfo();
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "pdf files (*.pdf)|*.pdf|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((fileName = openFileDialog1.FileName) != null)
{
startInfo = new ProcessStartInfo(fileName);
if (File.Exists(fileName))
{
i = 0;
foreach (String verb in startInfo.Verbs)
{
// Display the possible verbs.
MessageBox.Show(i.ToString() + ". " + verb);
i++;
}
}
}
//Console.WriteLine("Select the index of the verb.");
string index = "2";
if (Convert.ToInt32(index) < i)
verbToUse = startInfo.Verbs[Convert.ToInt32(index)];
else
return;
startInfo.Verb = verbToUse;
if (verbToUse.ToLower().IndexOf("printto") >= 0)
{
//Printer Name
arguments = #"\\hydfsvt02\HPLaserJ";
startInfo.Arguments = arguments;
}
Process newProcess = new Process();
newProcess.StartInfo = startInfo;
try
{
newProcess.Start();
MessageBox.Show(newProcess.ProcessName + " for file " + fileName + " started successfully with verb " + startInfo.Verb);
}
catch (System.ComponentModel.Win32Exception ex)
{
MessageBox.Show(" Win32Exception caught!");
MessageBox.Show(" Win32 error = " + ex.Message);
}
catch (System.InvalidOperationException)
{
MessageBox.Show("File " + fileName + " started with verb " + verbToUse);
}
}
I have written an application that does batch printing of PDF files.
It's not possible to specify the printer settings that you want to use. It's not even possible if you use the COM interface with the Adobe Standard/Pro versions.
Your options are to either:
Buy a license to a third-party PDF renderer that you can use to convert the PDF to Bitmaps and use the PrintDocument to control the PrinterSettings
Use something like GhostScript to convert the PDF files to BMP files and then use the PrintDocument class to print the BMP files. You can then control the PrinterSettings.
private void startPrintingButton_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (DialogResult.OK == ofd.ShowDialog(this))
{
PrintDocument pdoc = new PrintDocument();
pdoc.DefaultPageSettings.PrinterSettings.PrinterName = "ZDesigner GK420d";
pdoc.DefaultPageSettings.Landscape = true;
pdoc.DefaultPageSettings.PaperSize.Height = 140;
pdoc.DefaultPageSettings.PaperSize.Width = 104;
Print(pdoc.PrinterSettings.PrinterName, ofd.FileName);
}
}
private void Print(string printerName, string fileName)
{
try
{
ProcessStartInfo gsProcessInfo;
Process gsProcess;
gsProcessInfo = new ProcessStartInfo();
gsProcessInfo.Verb = "PrintTo";
gsProcessInfo.WindowStyle = ProcessWindowStyle.Hidden;
gsProcessInfo.FileName = fileName;
gsProcessInfo.Arguments = "\"" + printerName + "\"";
gsProcess = Process.Start(gsProcessInfo);
if (gsProcess.HasExited == false)
{
gsProcess.Kill();
}
gsProcess.EnableRaisingEvents = true;
gsProcess.Close();
}
catch (Exception)
{
}
}
This code will print PDF files as well as adjust the printing settings.