I have this simple code:
System.Drawing.Bitmap bm = bitmapSourceToBitmap(source);
try
{
bm.Save(#"C:\Seva\testeImagem.jpg");
}
catch (Exception ex)
{
}
This throws: Generic Error GDI+.
Anyway, I seached and people say that the problem is with permissions. How can I give permissions to it? Thanks
First find out under what credentials the code is running.
Then check (and, when needed, fix) the security/NTFS settings of the Seva folder.
Especially when this code is running from within a website or service the account will not have permissions to write to the folder.
instead of saving to C:\Seva\testeImagem.jpg why not try saving to
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"testeImagem.jpg");
You must ensure that the Seva folder exists under C:\ and ensure that the current user has permissions to write to\create this folder. Also, its considered bad practice to write to folders that the user doesn't own. If the user is Running As A Normal User (not an admin) failure to do so results in permission exceptions.
Could you test if the folder exists?
void BitmapCopy(System.Drawing.Bitmap source, string filename) {
if (!String.IsNullOrEmpty(filename) && (source != null)) {
string dirName = #"C:\Seva";
if (!System.IO.Directory.Exists(dirName)) {
dirName = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
}
string bmpFile = System.IO.Path.Combine(dirName, filename);
System.Drawing.Bitmap bm = bitmapSourceToBitmap(source);
try {
bm.Save(bmpFile);
} catch (ArgumentNullException ex) {
Console.WriteLine(ex.Message);
} catch (System.Runtime.InteropServices.ExternalException ex) {
Console.WriteLine(ex.Message);
}
}
}
Related
I am building a desktop application in WPF and it requires user preferences from an external text file. The file should be available for the user to directly manipulate after final building and publishing.
String settingsPath = "settings.txt";
try
{
if (!File.Exists(settingsPath))
throw new Exception("settings file does not exist");
String settingsText = File.ReadAllText(settingsPath);
MessageBox.Show(settingsText);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
Window.GetWindow(this).Close();
}
Even when I create a settings.txt file using file explorer, it throws the exception when built.
The text file you are creating is probably not in the working directory folder.
Use this code to diagnose your problem, it will show you where your code is looking for the file.
String settingsPath = "settings.txt";
try
{
if (!File.Exists(settingsPath))
throw new FileNotFoundException("settings file does not exist", Path.GetFullPath(settingsPath));
String settingsText = File.ReadAllText(settingsPath);
MessageBox.Show(settingsText);
}
catch (FileNotFoundException fileEx)
{
MessageBox.Show($"{fileEx.Message}:{fileEx.FileName}");
Window.GetWindow(this).Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
Window.GetWindow(this).Close();
}
I want to delete a file, in case it is locked by another process even though I have set try catch, but the program is still dark cash at fi.Delete(), so how to fix it.
A first chance exception of type 'System.UnauthorizedAccessException'
occurred in mscorlib.dll
Additional information: Access to the path 'H:\J\R\sound.MP4' is
denied.
private void GView_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
try
{
string cellValue = GView.Rows[e.RowIndex].Cells["NAME"].Value.ToString();
var confirmResult = MessageBox.Show("delete this item " + cellValue,
"Confirm Delete!!",
MessageBoxButtons.YesNo);
if (confirmResult == DialogResult.Yes)
{
System.IO.FileInfo fi = new System.IO.FileInfo(cellValue);
fi.Delete();
}
else
{
}
}
catch (UnauthorizedAccessException ex)
{
MessageBox.Show(ex.Message);
}
}
private void GView_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
try
{
string cellValue = GView.Rows[e.RowIndex].Cells["NAME"].Value.ToString();
var confirmResult = MessageBox.Show("delete this item " + cellValue,
"Confirm Delete!!",
MessageBoxButtons.YesNo);
if (confirmResult == DialogResult.Yes)
{
System.IO.FileInfo fi = new System.IO.FileInfo(cellValue);
fi.Delete();
}
else
{
}
}
catch(System.IO.IOException)
{
// exception when file is in use or any other
}
catch (UnauthorizedAccessException ex)
{
MessageBox.Show(ex.Message);
}
catch(Exception ex)
{
// all other
}
}
I read this article, as suggested by #Keyur PATEL, and figuring out this is a configuration of Visual Studio, I solved it by doing the following:
Navigate to "Debug / Exceptions / Common Language Runtime Exceptions / System"
Scroll down to where "NullReferenceException" is, and uncheck the "throw" checkbox, and check the "user-handled".
Thanks for your help
The user, whose account is used to run your application, must have access to that path
There are 2 ways to achieve this:
Configure a special application pool for your application, that will run under a user that has necessary permissions (can access admin shares on remote server). So your entire application will run under that account and have all its permissions.
Using impersonation to execute parts of your code under another account. This doesn't require any IIS configuration and is more secure and flexible than first way (for example? you can impersonate several accounts in a single application).
I have my program which has some Application Settings and some User Settings. On some machines my User Settings config file becomes corrupt and stops my program loading. I then log into the machine and delete the UserConfig directory stored at
%USERPROFILE%\Appdata\Local\MyApp
When my file is corrupt the error thrown is Configuration Settings Failed To Initialize so I was wondering if this happened in my program whether there was a way to delete the corrupt file and reset the configuration.
So far I have:
try
{
var prop1= Settings.Default.prop1;
}
catch (Exception ex)
{
var userSettingsLocation =
Path.Combine(Environment.ExpandEnvironmentVariables(
"%USERPROFILE%"), "AppData","Local", "MyApp");
if (Directory.Exists(userSettingsLocation))
{
DeleteDirectory(userSettingsLocation); // This is a reccursive
// delete method
// I need to reload settings
}
}
This deletes the file fine but if I try to read my settings again using for example: Settings.Reset(); I still get the same error. I need to somehow reset the configuration Settings after deleting the corrupt file. Is this possible?
So heres the trick if anyone else wants to know:
try
{
var prop1= Settings.Default.prop1;
}
catch (Exception ex)
{
var userSettingsLocation =
Path.Combine(Environment.ExpandEnvironmentVariables(
"%USERPROFILE%"), "AppData","Local", "MyApp");
if (Directory.Exists(userSettingsLocation))
{
if (ex.InnerException is System.Configuration.ConfigurationException)
{
var settingsFile = (ex.InnerException as ConfigurationException).Filename;
File.Delete(settingsFile);
System.Windows.Forms.Application.Restart();
}
}
}
Edit: after some trials, I think you need to restart the application after deleting the faulty config file. Here another SO thread: C# - User Settings broken
The last answer there is essentially the code you could use.
Actually I think you must call Settings.Reset after deleting the file.
By the way you should use the exception details to get the config file name causing the issue:
catch(Exception ex)
{
if(ex.InnerException is ConfigurationErrorsException)
{
var settingsFile = (e.InnerException as ConfigurationErrorsException).Filename;
/* ....Your code... */
}
}
string filename (()e.InnerException).Filename;
I'm currently trying to delete all files in a folder (Recently opened files), but without any luck, I get the message: "Access to the path 'C:\Users\User\Recent' is denied." . I've been looking around to see if there were any solutions, but unfortunately I can't find anything.
String recent = Environment.ExpandEnvironmentVariables("%USERPROFILE%") + "\\Recent";
EmptyFolderContents(recent);
private void EmptyFolderContents(string folderName)
{
foreach (var Folder in Directory.GetDirectories(folderName))
{
try
{
Directory.Delete(Folder, true);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
foreach (var Files in Directory.GetFiles(folderName))
{
try
{
File.Delete(Files);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
}
}
}
The reason you are getting the Access Denied error is because you can't just delete files from that folder. They are virtual paths to real files. There is probably a better way to do what you are doing.
Here is an alternative that I found here. It uses WinAPI, which is never fun, but it works.
//you'll need to add this.
using System.Runtime.InteropServices;
[DllImport("shell32.dll")]
public static extern void SHAddToRecentDocs(ShellAddToRecentDocsFlags flag, IntPtr pidl);
public enum ShellAddToRecentDocsFlags
{
Pidl = 0x001,
Path = 0x002,
}
//then call this from your method
SHAddToRecentDocs(ShellAddToRecentDocsFlags.Pidl, IntPtr.Zero);
Your error message seems to show that you're missing a backslash:
Access to the path 'C:Users\User\Recent' is denied.
(after the C:)
I Use Permissions Time Machine v1.1 to restore default permissions and remove "Access is denied" message for folder or files or registry keys or windows services or wmi objects it's free and fast and easy
download it from amyd projects blog
in my application i am start capinfos.exe that is part of Wireshark.
in the constructor i am check if Wireshark install on the machine:
private string _filePath = "";
public Capinfos(string capturePath)
{
if (Directory.Exists(#"C:\Program Files (x86)\Wireshark"))
{
_capInfos = #"C:\Program Files (x86)\Wireshark\capinfos.exe";
}
else if (Directory.Exists(#"C:\Program Files\Wireshark"))
{
_capInfos = #"C:\Program Files\Wireshark\capinfos.exe";
}
_filePath = capturePath;
}
what is the best way to do it and throw an exception if the file does not exist on the machine: please install Wireshark
private string _filePath = "";
public Capinfos(string capturePath) throws FileNotFoundException
{
if (Directory.Exists(#"C:\Program Files (x86)\Wireshark"))
{
_capInfos = #"C:\Program Files (x86)\Wireshark\capinfos.exe";
}
else if (Directory.Exists(#"C:\Program Files\Wireshark"))
{
_capInfos = #"C:\Program Files\Wireshark\capinfos.exe";
} else
{
throw new FileNotFoundException(#"Wireshark installation not found");
}
_filePath = capturePath;
}
You can then catch the exception by using this code:
try
{
Capinfos("path");
}
catch (FileNotFoundException ex)
{
Messagebox.Show("Please install wireshark.");
}
I don't have C# installed, this was written by hand. Hope it's fine!
Here's an excellent resource to learn on exceptions: http://msdn.microsoft.com/en-us/library/0yd65esw(v=vs.80).aspx
Something like:
throw new FileNotFoundException("Could not find " + _capInfos, _capInfos);
Not sure if this is what you want, but try to use a try-catch block. You could attempt to start the .exe in the try block and if it fails, throw a FileNotFoundException and create a popup box in the catch block that will alert the user of what they need to do.