How to recursively delete Registry Key using DeleteSubkeyTree - c#

Code:
try
{
RegistryKey SQMRegKey = Registry.LocalMachine.OpenSubKey("CurrentControlSet\\Control\\WMI\\Autologger", true);
//SQMRegKey.DeleteSubKey("SQMLogger");
SQMRegKey.DeleteSubKeyTree("SQMLogger");
SQMRegKey.Close();
}
catch (Exception ex)
{
MessageBox.Show(this, ex.ToString());
}
always throws exception System.NullReferenceException:Object reference not set to an instance of an object

The registry path is not correct. Please use the below modified code:
try
{
RegistryKey SQMRegKey = Registry.LocalMachine.OpenSubKey("System\\CurrentControlSet\\Control\\WMI\\Autologger", true);
//SQMRegKey.DeleteSubKey("SQMLogger");
SQMRegKey.DeleteSubKeyTree("SQMLogger");
SQMRegKey.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}

OpenSubKey may fail, in which case the return value is null. You use the reference, i.e. SQMRegKey without checking if it actually points to a valid object.
try
{
var SQMRegKey = Registry.LocalMachine.OpenSubKey("CurrentControlSet\\Control\\WMI\\Autologger", true);
if(SQMRegKey != null)
{
SQMRegKey.DeleteSubKeyTree("SQMLogger");
SQMRegKey.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(this, ex.ToString());
}

Related

Why does it not go into catch when it is not applicable to the try method?

why does the try fail and the catch doesn't go where I can click on the next page to find the fleet?
Code:
try
{
if (!_regRep.btnNext.Displayed && !_regRep.btnNext.Enabled)
{
_fleetRep.btnDelete(Fleetname).Click();
}
}
catch
{
if (_regRep.btnNext.Displayed && _regRep.btnNext.Enabled)
{
objCommon.Click(_regRep.btnNext);
_fleetRep.btnDelete(Fleetname).Click();
}
}
Ok solved guys a lot more cleaner:
try
{
if (_regRep.btnNext.Displayed && _regRep.btnNext.Enabled)
{
objCommon.Click(_regRep.btnNext);
_fleetRep.btnDelete(Fleetname).Click();
}
}
catch (Exception ex)
{
_fleetRep.btnDelete(Fleetname).Click();
Console.WriteLine("No delete found: " + ex.Message);
}

how to keep logs exception from catch and send logs to database c#?

I want to keep logs exception from catch and send to database or text file ?
try
{
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
thank you
This will create a text file or append the txt if it is already present with the date and time of the exception thrown. I hope this is what your were looking for.
catch(Exception Ex)
{
StreamWriter sw = null;
String Logfile = "C:\ExceptionLog.txt";
if (!System.IO.File.Exists(LogFile))
{
sw = File.CreateText(LogFile);
sw.WriteLine(String.Format("Exception\t DateTime"));
}
else
{
sw = File.AppendText(#"C:\ExceptionLog.txt");
}
sw.WriteLine(String.Format("{0}\t {1}", Ex,
DateTime.Now.ToString("MM/dd/yyy HH:mm:ss"));
sw.Close();
}
Simply, create object of your database context if you are using Entity
framework and insert it in your table(e.g. a table containing(id,
Exception Name, innermessage, error number, CreatedDateTime, etc)).
catch (Exception ex)
{
DatabaseEntity DbObj = new DatabaseEntity();
ExceptionTable ExObj = new ExceptionTable();
ExObj.ExceptionName = ex.Message;
ExObj.InnerException = ex.InnerException;
.....
//Code according to your need
.....
DbObj.ExceptionTable.Add(ExObj);
DbObj.SaveChanges();
MessageBox.Show(ex.Message);
}
you may follow this
How to Log Exception in a file?,
this may help you

Flurl exception not being caught

I don't understand why but I'm receiving Flurl Exceptions and those are not being caught by the try/catch block. Any ideas on why that's happening?
Here's the code:
try
{
var x = await Utils.Sales.GetUrl()
.PostJsonAsync(new Sale
{
MerchantId = Constants.Sandbox.MerchantId
})
.ReceiveJson<Sale>();
var b = x;
}
catch (FlurlHttpTimeoutException)
{
//LogError("Timed out!"); //todo:
}
catch (FlurlHttpException ex)
{
var x = ex.Message;
//todo:
//if (ex.Call.Response != null)
// LogError("Failed with response code " + call.Response.StatusCode);
//else
// LogError("Totally failed before getting a response! " + ex.Message);
}
catch (Exception ex)
{
var a = ex.Message;
}
Here's the output (the only reason why I know the exception is being thrown):
Maybe this page will help https://msdn.microsoft.com/zh-cn/library/jj619227.aspx
Sorry don't have a english version, you can try google translate it.
It's someting wrong with you catch exception type or await code.
Try this way catch your exception:
```
try
{
await t1;
}
catch (AggregateException ex)
{
var innerEx = ex.InnerExceptions[0];
if (innerEx is NotSupportedException)
{
...
}
else if (innerEx is NotImplementedException)
{
...
}
else
{
...
}
}
```

C# - How to make (Exception ex) as public

How can I make ex accessible after a try catch block?
Like this...
try
{
// do something...
}
catch (Exception ex) {
// skip here...
}
//execute **ex** here
Why do I want to do this?
If I write:
try
{
// do something...
// i already declared x as public.
x = "what ever";
}
catch (Exception ex) {
// if there's an error...
Console.WriteLine(ex);
}
// Even there's an error,
// there's still no output.
So maybe if ex is public, I can try this:
try
{
// do something...
}
catch (Exception ex) {
// skip here...
}
// execute **ex** here
I am not sure what you mean with "execute ex", but this is how you could access the Exception after the catch block:
Exception ex = null;
try
{
// do something...
}
catch (Exception ex1) {
ex = ex1;
}
if(ex != null)
// ...
Exception exceptionObject = null;
try
{
// do something...
}
catch (Exception ex) {
exceptionObject = ex;
}
// execute **ex** here
if(exceptionObject != null)
{
//do a thing
}
The thing you are doing is weird. Stop it.

Return in try & catch versus return in finally?

Is either one of these risky? Is one better? Or is it one of those things you print out and throw a dart at to decide?
I want to do this now that I understand how finally works:
try {
stuff that changes something...
}
catch (System.Exception ex) {
something.worked = false;
something.err = ex.Message;
}
finally {
stuff.close();
return something;
}
But I've seen:
try {
stuff that changes something...
return something;
}
catch (System.Exception ex) {
something.worked = false;
something.err = ex.Message;
return something;
}
finally {
stuff.close();
}
You can't return from finally. You will get compiler error:
Control cannot leave the body of a finally clause
If target class implements IDisposable then I would do next:
using (stuff s = new stuff())
{
return stuff;
}
or
using (stuff s = new stuff())
{
try
{
// do stuff
return stuff;
}
catch (Exception ex)
{
// do logging or another stuff
return something;
}
}
will call Dispose() for you if that will be required/possible.
Personally I would do neither and would use
try {
stuff that changes something...
}
catch (System.Exception ex) {
something.worked = false;
something.err = ex.Message;
}
finally {
stuff.close();
}
return something;
Also in the finally statement, check that you need to close/dispose of objects as they might have never been opened/set if they have failed.
Also see here Is it bad practice to return from within a try catch finally block?
There is no risk in the second approach. But it allows you to return different values in case of exceptions.

Categories