Does anyone know why the following will Open the Kool.exe however the Kool.exe cannot load all of its files unless i place the current projects debug/project.exe into the same folder as the Kool.exe it is trying to open?
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openF1 = new OpenFileDialog();
openF1.InitialDirectory = #"C:\";
openF1.Title = "Browse for Kool.exe...";
openF1.CheckFileExists = true;
openF1.CheckPathExists = true;
openF1.DefaultExt = "exe";
openF1.FileName = "Kool";
openF1.Filter = "Kool (*.exe)|*.exe|All Files(*.*)|*.*";
openF1.FilterIndex = 2;
openF1.RestoreDirectory = true;
openF1.ReadOnlyChecked = true;
openF1.ShowReadOnly = true;
if (openF1.ShowDialog() == DialogResult.OK)
{
Process[] pname = Process.GetProcessesByName(openF1.FileName);
if (pname.Length == 0)
{
Process.Start(openF1.FileName);
this.Close();
}
else
{
MessageBox.Show("Kool is already running.", "Patch: Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
}
}
else
{
MessageBox.Show("Cannot find Kool install", "Patch: Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
}
}
Other: I am running the application as an administrator.
Firstly, I doubt that this has anything to do with the file open dialog.
I strongly suspect that the problem is that Kool.exe assumes that the files it needs are in the current working directory, instead of trying to find them relative to the executable file itself.
Ideally, you should fix Kool.exe to be more resilient - but if that's not possible, just set the new process's working directory when you start it.
string file = openF1.FileName;
string directory = new FileInfo(file).Directory;
Process.Start(new ProcessStartInfo {
FileName = file,
WorkingDirectory = directory
});
Related
I have a project in ANN. To make it firstly i want to clone the picture to the local directory that can be accessed everytime in order to have indexing. The directory is
#"D:\assets\"
For the images, i'm using openfiledialog and multiselect is on.
For the container, i'm using this LOC:
> List<string[,]> path = new List<string[,]>();
The whole code is seperated. The first one is for browse and the second one is for copy the images to the directory that the first time i was mention.
For browse button:
List<string[,]> path = new List<string[,]>();
private void btnBrowse_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "File Extention|*.jpg;*.jpeg;*.bmp";
ofd.Multiselect = true;
if(ofd.ShowDialog() == DialogResult.OK)
{
foreach (var filename in ofd.FileNames)
{
imageList.Images.Add(filename, new Bitmap(filename));
var saveFileName = Path.GetFileName(filename);
var saveFileDir = Path.GetDirectoryName(filename);
lvFruit.Items.Add(saveFileName, filename);
string[,] input = new string[,] { {saveFileDir, saveFileName } };
path.Add(input);
}
}
}
For saving picture
private void btnSubmit_Click(object sender, EventArgs e)
{
String fruitname = txtFruitName.Text;
string appPath = #"D:\assets\";
if (txtFruitName.Text == "")
{
MessageBox.Show("Fruit Name Should be Filled");
}
else
{
int newindex = 0;
foreach (var item in path)
{
newindex += 1;
string iName = item[newindex - 1, 1].Trim();
string iPath = item[newindex - 1, 0].Trim();
try
{
File.Copy(iPath, appPath + iName, true);
File.SetAttributes(appPath, FileAttributes.Normal);
}
catch (Exception err)
{
MessageBox.Show(err.ToString());
//MessageBox.Show("Permission error or picture is already exists");
}
path.Clear();
}
MessageBox.Show("All Picture Has Been Saved");
lvFruit.Clear();
txtFruitName.Text = "";
btnDone.Enabled = true;
}
}
The images file is located at D:\pic and should be copied to D:\assets
The error is:
System.UnauthorizedAccessException: Access to the path 'D:\pic is denied
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.File.InternalCopy(String sourceFileName, String destFileName, Boolean overwrite, Boolean checkHost)
at System.IO.File.Copy(String sourceFileName, String destFileName,Boolean overwrite)
at Fruit_Dictionary.trainForm.btnSubmit_Click(Object sender EventArgs e) in D:\Fruit Dictionary\Fruit Dictionary\trainForm.cs:line 95
Do you know what the reason why it doesn't have any permited?
Actually i have run the program as administrator, and ofc i have check the permission in D:\pic and change it to do all permission.
I've been looking and surfing in internet for 2 days for just this reason, but i can't archieve anything. Any help will be helpful for me to accomplished this project.
Thank you :)
try to use a process to copy your files
foreach(String ImageOldPath in Paths)
{
try{
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = "C:\\Windows\\system32\\xcopy.exe";
info.Arguments = $"{ImageOldPath LocalPath} "
Console.WriteLine(info.Arguments);
info.UseShellExecute = false;
info.CreateNoWindow = true;
info.WindowStyle = ProcessWindowStyle.Hidden;
Process proc = new Process();
proc.StartInfo = info;
proc.Start();
proc.Dispose();
}catch(Exception e){}
}
UPDATE
ImageOldPath is the image old path in your case its called filename located in your foreach statement
Local path is appPath
I have a "work list style" application where the user selects a zip file from a list, then clicks a button to unzip it to a local folder.
Here is an extract from the code used:
ZipFile zip = Ionic.Zip.ZipFile.Read(sourcePackage);
zip.ExtractAll(destination);
zip.Dispose();
Everything works fine the first time but if the user tries to unzip the same file again (even after unzipping a few others), it goes too quick and all that is created in the destination folder is what looks like a temp file (e.g. 'x2hiex0z.pj0').
It's as if Ionic.Zip.ZipFile.Read is creating a cache of previously unzipped file names.
If so, how do I clear it so that I can force it to unzip the file again?
I gues you get some kind of a "File Exist"-Exception
Try:
OpenFileDialog open = new OpenFileDialog();
open.Filter = "zip Datei (.zip)|*.zip";
open.RestoreDirectory = true;
if (open.ShowDialog() == DialogResult.OK)
{
try
{
ZipFile zip = Ionic.Zip.ZipFile.Read(open.FileName);
zip.ExtractAll(".\\");
zip.Dispose();
}
catch (ZipException zex)
{
MessageBox.Show(zex.Message);
}
}
or with a Thread:
private void open()
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "zip Datei (.zip)|*.zip";
open.RestoreDirectory = true;
if (open.ShowDialog() == DialogResult.OK)
{
Thread t1 = new Thread
(delegate()
{
try
{
using (ZipFile zip = Ionic.Zip.ZipFile.Read(open.FileName))
{
zip.ExtractProgress += zip_ExtractProgress;
zip.ExtractAll(".\\", ExtractExistingFileAction.OverwriteSilently);
}
}
catch (ZipException zex)
{
error(zex.Message);
}
});
t1.IsBackground = true;
t1.Start();
}
}
private void zip_ExtractProgress(object sender, ExtractProgressEventArgs args)
{
update(args.TotalBytesToTransfer, args.BytesTransferred);
}
private void update(long ueTotal, long done)
{
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(() => { update(ueTotal, done); }));
}
else
{
if (ueTotal > 0)
{
double prz = (100d / ueTotal) * done;
lblProz.Text = prz.ToString("###.##");
}
}
}
I have a SaveFileDialog in my program. The issue is that when I click "Cancel" on the dialog, another SaveFileDialog opens up. But when I click cancel on the second SaveFileDialog, a third does NOT appear, so it's not a loop or anything like that. I can't see what is causing my SaveFileDialog to behave in such an odd manner. Obviously I need to fix this so that if the user clicks cancel on the first SaveFileDialog, it returns them to the form.
The code for saving in my program is as follows:
private void SaveFile()
{
if (filepath == null)
{
SaveFileAs();
}
else
{
StreamWriter sw = new StreamWriter(filepath);
try
{
sw.WriteLine(richTextBoxPrintCtrl1.Rtf);
richTextBoxPrintCtrl1.Modified = false;
sw.Close();
lastsave.Text = "Last Saved: " + DateTime.Now.ToString();
}
catch (Exception exc)
{
MessageBox.Show("Failed to save file. \n \n" + exc.Message);
}
finally
{
if (sw != null) sw.Close();
}
And SaveFileAs
private void SaveFileAs()
{
SaveFileDialog sfdSaveFile = new SaveFileDialog();//Creates a new instance of the SaveFileDialog
sfdSaveFile.Title = "Save File";//The title of the SaveFileDialog window
sfdSaveFile.FileName = "Untitled";//The default filename in the SaveFileDialog window
sfdSaveFile.Filter = "Rich Text Files (*.rtf)|*.rtf|Text Document (*.txt)|*.txt";//The supported file extensions when saving
if (sfdSaveFile.ShowDialog() == DialogResult.OK)//If the condition is correct, run the lines of code
try//try to run the code
{
filepath = sfdSaveFile.FileName;//get the filepath of the file once it is saved
SaveFile();//Calls the SaveFile object
this.Text = string.Format("{0} - Basic Word Processor", Path.GetFileName(sfdSaveFile.FileName));//Set the form name
lastsave.Text = "Last Saved: " + DateTime.Now.ToString();//Writes the text to the lastsave.Text label, followed by the current date and time
richTextBoxPrintCtrl1.Modified = false;
return;
}
catch (Exception exc)//Catches any errors
{
MessageBox.Show("An error occured whilst saving. " + exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (sfdSaveFile.ShowDialog() == DialogResult.Cancel)
{
return;
}
else if (sfdSaveFile.ShowDialog() == DialogResult.Cancel)//If the condition is true, run the line of code
{
return;
}
If anyone could help me determine why this is occurring, I'd really appreciate it..
--EDIT--
I forgot to mention that if the user does go through and save the file, the SaveFileDialog doesn't open up another SaveFileDialog. It is something to do with cancelling the SaveFileDialog which causes the issue.
sfdSaveFile.ShowDialog() opens the file dialog. If it's not DialogResult.OK the first time, it goes to the else clause and gets called again. Store the result of ShowDialog and check what it is, don't call it every time.
In order to do so, use this sort of if/else:
DialogResult dialogResult = sfdSaveFile.ShowDialog();
if (dialogResult == DialogResult.OK)
{
}
else if (dialogResult == DialogResult.Cancel)
{
}
I have the following code:
Open File Code
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Open File";
ofd.FileName = "";
ofd.Filter = "Rich Text Files (*.rtf)|*.rtf|Text Document (*.txt)|*.txt|Microsoft Word Document (*.doc)|*.doc|Hypertext Markup Language Document (*.html)|*.html"; StreamReader sr = null;
if (ofd.ShowDialog() != DialogResult.Yes) return;
{
NewFile();
}
try
{
sr = new StreamReader(ofd.FileName);
this.Text = string.Format("{0} - Basic Word Processor", Path.GetFileName(ofd.FileName));
richTextBoxPrintCtrl1.Text = ofd.FileName;
richTextBoxPrintCtrl1.Text = sr.ReadToEnd();
filepath = ofd.FileName;
richTextBoxPrintCtrl1.LoadFile(fileName, RichTextBoxStreamType.RichText);
}
catch
{
}
finally
{
if (sr != null) sr.Close();
}
New File Code
if (richTextBoxPrintCtrl1.Modified)
{
DialogResult r = MessageBox.Show(this, "Save Current Document?", "Save?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
if (r == DialogResult.Yes) SaveFile();
if (r == DialogResult.Cancel) return;
}
this.Text = string.Format("Untitled - Basic Word Processor");
richTextBoxPrintCtrl1.Text = "";
filepath = null;
}
}
SaveFileAs Code
SaveFileDialog sfdSaveFile = new SaveFileDialog();
sfdSaveFile.Title = "Save File";
sfdSaveFile.FileName = "Untitled";
sfdSaveFile.Filter = "Rich Text Files (*.rtf)|*.rtf|Text Document (*.txt)|*.txt|Microsoft Word Document (*.doc)|*.doc|Hypertext Markup Language Document (*.html)|*.html";
if (sfdSaveFile.ShowDialog() == DialogResult.OK)
try
{
filepath = sfdSaveFile.FileName;
SaveFile();
this.Text = string.Format("{0} - Basic Word Processor", Path.GetFileName(sfdSaveFile.FileName));
}
catch (Exception exc)
{
}
SaveFile Code
if (filepath == null)
{
SaveFileAs();
return;
}
StreamWriter sw = new StreamWriter(filepath);
//StreamWriter stwrite = null;
try
{
sw.WriteLine(richTextBoxPrintCtrl1.Text);
richTextBoxPrintCtrl1.Modified = false;
sw.Close();
}
catch (Exception e)
{
MessageBox.Show("Failed to save file. \n" + e.Message);
}
finally
{
if (sw != null) sw.Close();
}
Currently, the program skips the NewFile event (even if the text has been modified). How can I make it so that when I click "Open", it asks me if I would like to save (if the text is modified). Then if I click cancel, it returns me to the form?
Sorry. I'm really new to programming so this is all a learning curve.
Okay, I think I see what's going on here. First off I don't believe return; works the way you think it does.
if (ofd.ShowDialog() != DialogResult.Yes) return;
{
NewFile();
}
You have a return; call that happens if the show dialog is not yes. The { newFile() } code doesn't need braces around it. So those lines are really:
if (ofd.ShowDialog() != DialogResult.Yes) return;
NewFile();
Now, given your requirement, NewFile is called WAY too late in the game anyway. You want that to happen before you ask them what to open; just like most other windows programs work.
But, there's another issue. Your return statement in the NewFile method is simply returning from NewFile. It's not telling the previous method to bail out.
So the NewFile method needs a return type to indicate whether to allow the calling method to go forward or not.
And, looking at your save file you have a return method there too. What's with all of the return; calls?
Which brings us back to how do we fix this?
Answer: rewrite the whole thing. Starting with the following method:
private Boolean CanClear() {
Boolean result = false;
if (richTextBoxPrintCtrl1.Modified)
{
DialogResult r = MessageBox.Show(this, "Save Current Document?", "Save?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
if (r == DialogResult.Yes) {
SaveFile();
result = true;
}
} else {
result = true;
}
return result;
}
Now, in your Open and New file methods do the following (assuming these are the method headers)
protected void OpenFile(...) {
if (!CanClear()) return;
.... now execute the code to load the open dialog and the selected file.
}
protected void NewFile(...) {
if (!CanClear()) return;
this.Text = string.Format("Untitled - Basic Word Processor");
richTextBoxPrintCtrl1.Text = "";
filepath = null;
}
The problem is here:
if (ofd.ShowDialog() != DialogResult.Yes) return;
{
NewFile();
}
remove that return. But, as #Chris says, you should ask whether to save the current file or not before the user selects the new file to open.
try
{
OpenFileDialog dialog = new OpenFileDialog();
String appData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
string tempPath = System.IO.Path.GetTempPath();
dialog.InitialDirectory = tempPath;
dialog.Multiselect = true;
dialog.Filter = "Temp files (*.tmp)|*.tmp";
dialog.ValidateNames = false;
if (dialog.ShowDialog() == DialogResult.OK)
{
string[] filePaths = dialog.SafeFileNames;
foreach (string s in filePaths)
richTextBox1.Text += s;
//MessageBox.Show("");
}
}
catch
{
MessageBox.Show("Error Occured");
}
when i selecting files (which already in use in another application) in openfiledialog I getting error but still I want their paths...
This is apparantly an issue with OpenFileDialog and MultiSelect "true." See this post for a discussion on the problem (and some possible solutions):
http://social.msdn.microsoft.com/forums/en-US/netfxbcl/thread/56fbbf9b-31d5-4e89-be85-83d9cb1d538c/
Setting openFileDialog.ValidateNames = false; worked for me.
try
String tempPath = System.IO.Path.GetDirectoryName(dialog.FileName) + #"\";