openfiledialog error for selecting used files - c#

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) + #"\";

Related

C# Windows Application File: have no access for File.Copy

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

Open a executable through filedialog this is getting errors - Why?

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
});

SaveFileDialog removes extension from set filename

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.

How do I make it so that when the user clicks cancel, it cancels the dialog?

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.

How to set Printer Settings while printing PDF

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.

Categories