I want to access the RegistryKeys of a remote PC in my network, if there is no terminalNumber passed as a parameter.
public LoginEntity(string ipAdress, string username, string password, string terminalNumber = "")
{
this.IpAdress = ipAdress;
this.Username = username;
this.Password = password;
if (terminalNumber == "")
{
try
{
RegistryKey rKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, IpAdress, RegistryView.Registry64);
rKey = rKey.OpenSubKey(#"SOFTWARE\Test", RegistryKeyPermissionCheck.ReadWriteSubTree);
var key = rKey.GetValue("terminalNumber", "NOTFOUND");
if (key is string)
{
if ((string)key != "NOTFOUND")
this.TerminalNumber = (string)key;
}
}
catch (UnauthorizedAccessException ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("UnauthorizedException: Calling TerminalNumber from Remote Registry Keys");
}
catch (IOException ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("IOException: Remote PC not available");
}
}
else
this.TerminalNumber = terminalNumber;
}
Due to safety reasons the Subkey in this example is called 'Test'.
But at
RegistryKey rKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, IpAdress, RegistryView.Registry64);
the application throws an UnauthorizedAccessException.
What I did:
I already run Visual Studio 2019 as an administator.
The LoginEntity was instantiated in a Task*. (As I am using WPF, I don't want my UI to freeze, so I run it in a Task).
*The Task call is located in the MainWindow()-Constructor of my WPF-Application
Task.Run(() =>
{
List<LoginEntity> loginUser = Utility.ReadLoginDataFromCsv(loginUserPath);
this.Dispatcher.Invoke(() =>
{
Listview.ItemsSource = loginUser;
lblUserLoading.Content = "";
});
});
public static List<LoginEntity> ReadLoginDataFromCsv(string path, bool ignoreFirstLine = false)
{
List<LoginEntity> list = new List<LoginEntity>();
var lines = File.ReadAllLines(path, Encoding.UTF8);
if (ignoreFirstLine)
lines = lines
.Skip(1)
.ToArray();
foreach (string line in lines)
{
var rowData = line.Split(';');
LoginEntity le = new LoginEntity(rowData[0], rowData[1], rowData[2], rowData[3]);
if (le.IpAdress != "" && le.Username != "" && le.Password != "")
list.Add(le);
}
return list;
}
Does anyone know why I get the UnAuthorizedException and how I can get rid of it?
Related
I have created my app in Visual Studio 2019 for Android and iOS.
If I DEBUG my iOS app it is working perfectly as it should. It is debugged with iPhoneSimulator.
But if I rollout my RELEASE and test in on for example iPad, it seems that it can not find the SQLite DB whitch is stored like this:
string dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "MyDatabase.db");
Is there a problem maybe with the SpecialFolder 'Personal' on iOS?
This code will be processes during start up:
if (!File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "MyDatabase.db")))
{
DataHelper.Database db = new DataHelper.Database();
if (!db.CreateDatabase())
{
DisplayAlert("Error", "DB could not be loaded !", "OK");
}
}
this is my DatabaseHelper class:
namespace VoTa.DataHelper
{
public class Database
{
readonly string dbpath = Data.GetPath();
private static readonly string ftpurl = "myURL";
public bool CreateDatabase()
{
try
{
var connection = new SQLiteConnection(dbpath);
connection.CreateTable<Belohnungen>();
connection.CreateTable<Vokabeln>();
connection.CreateTable<EigeneVokabel>();
connection.Close();
return true;
}
catch (SQLiteException)
{
//Log.Info("SQLite Fehler!", ex.Message);
return false;
}
}
public void InsertIntoVokabeln(string dateiname)
{
String voakbelURL = ftpurl + dateiname;
string id;
string fremdsprache;
string deutsch;
string info1;
string info2;
var connection = new SQLiteConnection(dbpath);
connection.Query<Vokabeln>("Delete from Vokabeln");
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(voakbelURL);
var vList = xmldoc.SelectNodes("/Vokabel/VokabelModel");
try
{
foreach (XmlNode node in vList)
{
id = node["Id"].InnerText;
fremdsprache = node["fremdsprache"].InnerText;
deutsch = node["deutsch"].InnerText;
info1 = "";
info2 = "";
if (node["info1"] != null)
{
info1 = node["info1"].InnerText;
}
if (node["info2"] != null)
{
info1 = node["info2"].InnerText;
}
Vokabeln vokabel = new Vokabeln
{
Fremdsprache = fremdsprache,
Deutsch = deutsch,
Info1 = info1,
Info2 = info2
};
connection.Insert(vokabel);
}
}
catch (Exception)
{
return;
}
finally
{
connection.Close();
}
}
public void InsertIntoBelohnungen(string dateiname)
{
String belohunngURL = ftpurl + dateiname;
string id;
string beloh;
string info1;
string info2;
var connection = new SQLiteConnection(dbpath);
connection.Query<Belohnungen>("Delete from Belohnungen");
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(belohunngURL);
var vList = xmldoc.SelectNodes("/Belohnung/BelohnungModel");
try
{
foreach (XmlNode node in vList)
{
id = node["Id"].InnerText;
beloh = node["Belohnung"].InnerText;
info1 = "";
info2 = "";
if (node["info1"] != null)
{
info1 = node["info1"].InnerText;
}
if (node["info2"] != null)
{
info1 = node["info2"].InnerText;
}
Belohnungen belohnung = new Belohnungen
{
Belohnung = beloh,
Info1 = info1,
Info2 = info2
};
connection.Insert(belohnung);
}
}
catch (Exception)
{
return;
}
finally
{
connection.Close();
}
}
It is working on iPhoneSimulator but not in "real".
Add DB file in the AppDelegate.cs file like:
string sqliteFilename = "MyDatabase.db";
string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal),"..","Library");
string dbpath = Path.Combine(folderPath, sqliteFilename);
LoadApplication(new App(dbpath));
My App.xaml.cs:
public App(string dbpath)
{
InitializeComponent();
Data.SetPath(dbpath);
MainPage = new NavigationPage(new MainPage());
}
My MainView:
switch (Device.RuntimePlatform)
{
case Device.iOS:
if (!File.Exists(Data.GetPath()))
{
DataHelper.Database db = new DataHelper.Database();
if (!db.CreateDatabase())
{
DisplayAlert("Fehler", "Datenbank konnte nicht erstellt werden !", "OK");
}
}
break;
case Device.Android:
if (!File.Exists(Data.GetPath()))
{
DataHelper.Database db = new DataHelper.Database();
if (!db.CreateDatabase())
{
DisplayAlert("Fehler", "Datenbank konnte nicht erstellt werden !", "OK");
}
}
break;
}
This does not gave me exception.
I get this exception:
private void Starten()
{
DataHelper.Database db = new DataHelper.Database();
try
{
List<Vokabeln> myvokabel = db.SelectTableVokabeln(anzahlVokabel).ToList();
frage.Clear();
antwort.Clear();
info1.Clear();
info2.Clear();
belohnung.Clear();
int test = myvokabel.Count();
foreach (var item in myvokabel)
{
if (richtung == 1)
{
frage.Add(item.Deutsch);
antwort.Add(item.Fremdsprache);
}
else
{
frage.Add(item.Fremdsprache);
antwort.Add(item.Deutsch);
info1.Add(item.Info1);
info2.Add(item.Info2);
}
}
List<Belohnungen> mybelohnung = db.SelectTableBelohnungen().ToList();
foreach (var bel in mybelohnung)
{
belohnung.Add(bel.Belohnung);
}
//DisplayAlert("Info", "Vokabeln und Belohnungen wurden geladen!", "OK");
}
catch (Exception)
{
//Log.Info("interner Fehler!", ex.Message);
DisplayAlert("Fehler", "Es ist ein Fehler aufgetreten", "OK");
}
}
Database.cs
public List<Vokabeln> SelectTableVokabeln(int anzahl)
{
try
{
var connection = new SQLiteConnection(dbpath);
var abfrage = connection.Query<Vokabeln>(string.Format("SELECT ID, Fremdsprache, Deutsch, Info1, Info2 FROM Vokabeln ORDER BY RANDOM() LIMIT {0}", anzahl));
//return connection.Table<Vokabeln>().ToList();
return abfrage;
}
catch (SQLiteException)
{
//Log.Info("SQLite Fehler!", ex.Message);
return null;
}
}
public List<Belohnungen> SelectTableBelohnungen()
{
try
{
var connection = new SQLiteConnection(dbpath);
return connection.Table<Belohnungen>().ToList();
}
catch (SQLiteException)
{
//Log.Info("SQLite Fehler!", ex.Message);
return null;
}
}
Any help?
Thank you.
I remember having had similar issues when trying to handle the file in shared code.
Strangely enough, creating an interface in my shared code with a native implementation on both iOS and Android resolved the issue.
Here is my code to retrieve the connection from within my iOS project in a native implementation of an interface from the shared project called IFileService:
public SQLite.SQLiteConnection GetDbConnection()
{
try
{
string sqliteFilename = "MyAppDb.db3";
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal) + sqliteFilename);
SQLiteConnection conn = new SQLite.SQLiteConnection(path, SQLiteOpenFlags.Create | SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.NoMutex);
return conn;
}
catch (Exception ex)
{
Logger.Fatal(ex, "An exception occurred at GetConnection");
Logger.Trace("Stack Trace: {0}", ex.StackTrace);
}
return null;
}
Also I would suggest that you don't access your connection the way you are doing it right now, as
var connection = new SQLiteConnection(dbpath);
will keep your connection open, which will most probably cause problems, if you want to use another connection.
In order to ensure that your connection is properly closed, I would highly recommend to manage it in a using block:
using(SQLiteConnection connection = iFileService.GetDbConnection())
{
connection.CreateTable<Belohnungen>();
connection.CreateTable<Vokabeln>();
connection.CreateTable<EigeneVokabel>();
}
This way the connection will be properly closed and disposed when your database access is finished. Also ensure that you always access your database connections that way whenever you get or store data in SQLite.
P.S.: if you are using a newer version of sqlite, you might need to construct your database with
SQLiteConnection connection = new SQLiteConnection(dbpath);
instead of the way I am creating it.
I will be straight forward and say that I found this code online and therefore is not my own. It works perfectly if I type in the name of the program as shown in Programs and Features but for instance, I want to type Mozilla Firefox and have it find the installed Mozilla Firefox 26.0 (x86 en-US). I tried many times to use .substring and .contains in the line that checks the two strings but each time leads the program to just lock up. Any help is appreciated.
Just for side notes:
I am using a list of programs in a txt file that are read in to check against the installed apps.
I ran a messagebox right after it sets the display name and several of the message boxes show up blank. I tried to limit it with string.length not being 0 and length being equal or greater than the string from the txt file but all still locks up the program.
Code:
private static bool IsAppInstalled(string p_machineName, string p_name)
{
string keyName;
// search in: CurrentUser
keyName = #"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
if (ExistsInRemoteSubKey(p_machineName, RegistryHive.CurrentUser, keyName, "DisplayName", p_name) == true)
{
return true;
}
// search in: LocalMachine_32
keyName = #"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
if (ExistsInRemoteSubKey(p_machineName, RegistryHive.LocalMachine, keyName, "DisplayName", p_name) == true)
{
return true;
}
// search in: LocalMachine_64
keyName = #"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall";
if (ExistsInRemoteSubKey(p_machineName, RegistryHive.LocalMachine, keyName, "DisplayName", p_name) == true)
{
return true;
}
return false;
}
private static bool ExistsInRemoteSubKey(string p_machineName, RegistryHive p_hive, string p_subKeyName, string p_attributeName, string p_name)
{
RegistryKey subkey;
string displayName;
using (RegistryKey regHive = RegistryKey.OpenRemoteBaseKey(p_hive, p_machineName))
{
using (RegistryKey regKey = regHive.OpenSubKey(p_subKeyName))
{
if (regKey != null)
{
foreach (string kn in regKey.GetSubKeyNames())
{
using (subkey = regKey.OpenSubKey(kn))
{
displayName = subkey.GetValue(p_attributeName) as string;
MessageBox.Show(displayName);
if (p_name.Equals(displayName, StringComparison.OrdinalIgnoreCase) == true) // key found!
{
return true;
}
}
}
}
}
}
return false;
}
I have tried too many different things to list (or remember)... If it helps this is the majority of the rest of the code calling it:
private void Button_Click(object sender, EventArgs e)
{
string[] lines = new string[250];
string msg = "";
string path = System.Windows.Forms.Application.StartupPath;
if (blah.Checked)
{
try
{
StreamReader filePick = new StreamReader(#path + "\\blah.txt");
int counter = 0;
while ((lines[counter] = filePick.ReadLine()) != null)
{
counter++;
}
filePick.Close();
}
catch (Exception ex)
{
msg += ex.Message;
}
}
else if (blah2.Checked)
{
try
{
StreamReader filePick = new StreamReader(#path + "\\blah2.txt");
int counter = 0;
while ((lines[counter] = filePick.ReadLine()) != null)
{
counter++;
}
filePick.Close();
}
catch (Exception ex)
{
msg += ex.Message;
}
}
string MACHINE_NAME = System.Environment.MachineName;
int counter2 = 0;
string APPLICATION_NAME = "";
string filename = "";
while (lines[counter2] != null)
{
APPLICATION_NAME = lines[counter2];
try
{
bool isAppInstalled = IsAppInstalled(MACHINE_NAME, APPLICATION_NAME);
if (isAppInstalled == true)
{
appsNeedAttention = true;
msg += APPLICATION_NAME + " is still installed.";
}
counter2++;
}
catch (Exception ex)
{
msg += ex.Message;
}
}
if (blah.Checked == true)
{
filename = "blah.txt";
}
else if (blah2.Checked == true)
{
filename = "blah2.txt";
}
if (counter2 == 0 && File.Exists(filename) == true)
{
msg = "There are no programs listed in the file.";
}
if (msg != "")
{
MessageBox.Show(msg, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
Try to change this part :
if (p_name.Equals(displayName, StringComparison.OrdinalIgnoreCase) == true)
{
return true;
}
To this :
//check null to avoid error
if (!string.IsNullOrEmpty(displayName))
{
//convert both string to lower case to ignore case difference
//and use contains to match partially
if (displayName.ToLower().Contains(p_name.ToLower()))
{
return true;
}
}
I am running a loop in C# that reads a file and make updates to the MySQL database with MySQL ODBC 5.1 driver in a Windows 8 64-bit environment.
The operations is simple
Count +1
See if file exists
Load XML file(XDocument)
Fetch data from XDocument
Open ODBCConnection
Run a couple of Stored Procedures against the MySQL database to store data
Close ODBCConnection
The problem is that after a while it will hang on for example a OdbcCommand.ExecuteNonQuery. It is not always the same SP that it will hang on?
This is a real problem, I need to loop 60 000 files but it only last around 1000 at a time.
Edit 1:
The problem seemse to accure here hever time :
public bool addPublisherToGame(int inPublisherId, int inGameId)
{
string sqlStr;
OdbcCommand commandObj;
try
{
sqlStr = "INSERT INTO games_publisher_binder (gameId, publisherId) VALUE(?,?)";
commandObj = new OdbcCommand(sqlStr, mainConnection);
commandObj.Parameters.Add("#gameId", OdbcType.Int).Value = inGameId;
commandObj.Parameters.Add("#publisherId", OdbcType.Int).Value = inPublisherId;
if (Convert.ToInt32(executeNonQuery(commandObj)) > 0)
return true;
else
return false;
}
catch (Exception ex)
{
throw (loggErrorMessage(this.ToString(), "addPublisherToGame", ex, -1, "", ""));
}
finally
{
}
}
protected object executeNonQuery(OdbcCommand inCommandObj)
{
try
{
//FileStream file = new FileStream("d:\\test.txt", FileMode.Append, FileAccess.Write);
//System.IO.StreamWriter stream = new System.IO.StreamWriter(file);
//stream.WriteLine(DateTime.Now.ToString() + " - " + inCommandObj.CommandText);
//stream.Close();
//file.Close();
//mainConnection.Open();
return inCommandObj.ExecuteNonQuery();
}
catch (Exception ex)
{
throw (ex);
}
}
I can see that the in parameters is correct
The open and close of the connection is done in a top method for ever loop (with finally).
Edit 2:
This is the method that will extract the information and save to database :
public Boolean addBoardgameToDatabase(XElement boardgame, GameFactory gameFactory)
{
int incomingGameId = -1;
XElement tmpElement;
string primaryName = string.Empty;
List<string> names = new List<string>();
GameStorage externalGameStorage;
int retry = 3;
try
{
if (boardgame.FirstAttribute != null &&
boardgame.FirstAttribute.Value != null)
{
while (retry > -1)
{
try
{
incomingGameId = int.Parse(boardgame.FirstAttribute.Value);
#region Find primary name
tmpElement = boardgame.Elements("name").Where(c => c.Attribute("primary") != null).FirstOrDefault(a => a.Attribute("primary").Value.Equals("true"));
if (tmpElement != null)
primaryName = tmpElement.Value;
else
return false;
#endregion
externalGameStorage = new GameStorage(incomingGameId,
primaryName,
string.Empty,
getDateTime("1/1/" + boardgame.Element("yearpublished").Value),
getInteger(boardgame.Element("minplayers").Value),
getInteger(boardgame.Element("maxplayers").Value),
boardgame.Element("playingtime").Value,
0, 0, false);
gameFactory.updateGame(externalGameStorage);
gameFactory.updateGameGrade(incomingGameId);
gameFactory.removeDesignersFromGame(externalGameStorage.id);
foreach (XElement designer in boardgame.Elements("boardgamedesigner"))
{
gameFactory.updateDesigner(int.Parse(designer.FirstAttribute.Value), designer.Value);
gameFactory.addDesignerToGame(int.Parse(designer.FirstAttribute.Value), externalGameStorage.id);
}
gameFactory.removePublishersFromGame(externalGameStorage.id);
foreach (XElement publisher in boardgame.Elements("boardgamepublisher"))
{
gameFactory.updatePublisher(int.Parse(publisher.FirstAttribute.Value), publisher.Value, string.Empty);
gameFactory.addPublisherToGame(int.Parse(publisher.FirstAttribute.Value), externalGameStorage.id);
}
foreach (XElement element in boardgame.Elements("name").Where(c => c.Attribute("primary") == null))
names.Add(element.Value);
gameFactory.removeGameNames(incomingGameId);
foreach (string name in names)
if (name != null && name.Length > 0)
gameFactory.addGameName(incomingGameId, name);
return true;
}
catch (Exception)
{
retry--;
if (retry < 0)
return false;
}
}
}
return false;
}
catch (Exception ex)
{
throw (new Exception(this.ToString() + ".addBoardgameToDatabase : " + ex.Message, ex));
}
}
And then we got one step higher, the method that will trigger addBoardgameToDatabase :
private void StartThreadToHandleXmlFile(int gameId)
{
FileInfo fileInfo;
XDocument xmlDoc;
Boolean gameAdded = false;
GameFactory gameFactory = new GameFactory();
try
{
fileInfo = new FileInfo(_directory + "\\" + gameId.ToString() + ".xml");
if (fileInfo.Exists)
{
xmlDoc = XDocument.Load(fileInfo.FullName);
if (addBoardgameToDatabase(xmlDoc.Element("boardgames").Element("boardgame"), gameFactory))
{
gameAdded = true;
fileInfo.Delete();
}
else
return;
}
if (!gameAdded)
{
gameFactory.InactivateGame(gameId);
fileInfo.Delete();
}
}
catch (Exception)
{ throw; }
finally
{
if(gameFactory != null)
gameFactory.CloseConnection();
}
}
And then finally the top level :
public void UpdateGames(string directory)
{
DirectoryInfo dirInfo;
FileInfo fileInfo;
Thread thread;
int gameIdToStartOn = 1;
dirInfo = new DirectoryInfo(directory);
if(dirInfo.Exists)
{
_directory = directory;
fileInfo = dirInfo.GetFiles("*.xml").OrderBy(c=> int.Parse(c.Name.Replace(".xml",""))).FirstOrDefault();
gameIdToStartOn = int.Parse(fileInfo.Name.Replace(".xml", ""));
for (int gameId = gameIdToStartOn; gameId < 500000; gameId++)
{
try
{ StartThreadToHandleXmlFile(gameId); }
catch(Exception){}
}
}
}
Use SQL connection pooling by adding "Pooling=true" to your connectionstring.
Make sure you properly close the connection AND the file.
You can create one large query and execute it only once, I think it is a lot faster then 60.000 loose queries!
Can you show a bit of your code?
I have a windows applicaiton c# catching the url of a running firefox instance.
I have always used "MozillaContentWindow" to get firefox URL but i dont understand why it dont work anymore.
string s = GetUrlFromBrowsersWithIdentifier("MozillaContentWindow", foreGround);
public string GetUrlFromBrowsersWithIdentifier(string identifier, int foreground)
{
try
{
IntPtr ptr = new IntPtr(foreground);
var aeBrowser = AutomationElement.FromHandle(ptr);
return aeBrowser == null ? "" : GetURLfromBrowser(aeBrowser, identifier);
}
catch (Exception ex)
{
return "";
}
}
string GetURLfromBrowser(AutomationElement rootElement, string identifier)
{
try
{
Condition condition1 = new PropertyCondition(AutomationElement.IsContentElementProperty, true);
Condition condition2 = new PropertyCondition(AutomationElement.ClassNameProperty, identifier);
var walker = new TreeWalker(new AndCondition(condition1, condition2));
var elementNode = walker.GetFirstChild(rootElement);
if (elementNode != null)
{
var p = elementNode.GetSupportedPatterns();
if (p.Any(autop => autop.ProgrammaticName.Equals("ValuePatternIdentifiers.Pattern")))
{
var valuePattern = elementNode.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;
if (valuePattern != null)
return (valuePattern.Current.Value);
}
}
}
catch
{
return "";
}
return "";
}
Now when it enters "walker.GetFirstChild(rootElement);" it just stops there. I cant figure out why. This only happend on latest version of firefox.
Did they change the name of the value bar containing the url?
Thank you
Try using MozillaWindowContentClass for newer versions.
I would like to know if there's a way to list the SQL Server instances installed on the local computer.
SqlDataSourceEnumerator and EnumAvailableSqlServers don't do the trick as I don't need the instances that are over the local network.
Direct access to Windows Registry isn't the recommended solution by MS, because they can change keys/paths. But I agree that SmoApplication.EnumAvailableSqlServers() and SqlDataSourceEnumerator.Instance fails providing instances on 64-bit platforms.
Getting data from Windows Registry, keep in mind the difference in Registry access between x86 and x64 platforms. 64-bit edition of Windows stores data in different parts of system registry and combines them into views. So using RegistryView is essential.
using Microsoft.Win32;
RegistryView registryView = Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32;
using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView))
{
RegistryKey instanceKey = hklm.OpenSubKey(#"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL", false);
if (instanceKey != null)
{
foreach (var instanceName in instanceKey.GetValueNames())
{
Console.WriteLine(Environment.MachineName + #"\" + instanceName);
}
}
}
If you are looking for 32-bit instances on a 64-bit OS (pretty weird, but possible), you will need to look:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Microsoft SQL Server
You could call EnumAvailableSQlServers with a localOnly = True
public static DataTable EnumAvailableSqlServers(bool localOnly)
See MSDN docs for EnumAvailableSqlServers
SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance;
System.Data.DataTable table = instance.GetDataSources();
foreach (System.Data.DataRow row in table.Rows)
{
if (row["ServerName"] != DBNull.Value && Environment.MachineName.Equals(row["ServerName"].ToString()))
{
string item = string.Empty;
item = row["ServerName"].ToString();
if(row["InstanceName"] != DBNull.Value || !string.IsNullOrEmpty(Convert.ToString(row["InstanceName"]).Trim()))
{
item += #"\" + Convert.ToString(row["InstanceName"]).Trim();
}
listview1.Items.Add(item);
}
}
you can use registry to get sql server instance name in local system
private void LoadRegKey()
{
RegistryKey key = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names");
foreach (string sk in key.GetSubKeyNames())
{
RegistryKey rkey = key.OpenSubKey(sk);
foreach (string s in rkey.GetValueNames())
{
MessageBox.Show("Sql instance name:"+s);
}
}
}
Combined several methods:
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Smo.Wmi;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using Microsoft.Win32;
namespace SqlServerEnumerator
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, Func<List<string>>> methods = new Dictionary<string, Func<List<string>>>
{
{"CallSqlBrowser", GetLocalSqlServerInstancesByCallingSqlBrowser},
{"CallSqlWmi32", GetLocalSqlServerInstancesByCallingSqlWmi32},
{"CallSqlWmi64", GetLocalSqlServerInstancesByCallingSqlWmi64},
{"ReadRegInstalledInstances", GetLocalSqlServerInstancesByReadingRegInstalledInstances},
{"ReadRegInstanceNames", GetLocalSqlServerInstancesByReadingRegInstanceNames},
{"CallSqlCmd", GetLocalSqlServerInstancesByCallingSqlCmd},
};
Dictionary<string, List<string>> dictionary = methods
.AsParallel()
.ToDictionary(v => v.Key, v => v.Value().OrderBy(n => n, StringComparer.OrdinalIgnoreCase).ToList());
foreach (KeyValuePair<string, List<string>> pair in dictionary)
{
Console.WriteLine(string.Format("~~{0}~~", pair.Key));
pair.Value.ForEach(v => Console.WriteLine(" " + v));
}
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
private static List<string> GetLocalSqlServerInstancesByCallingSqlBrowser()
{
DataTable dt = SmoApplication.EnumAvailableSqlServers(true);
return dt.Rows.Cast<DataRow>()
.Select(v => v.Field<string>("Name"))
.ToList();
}
private static List<string> GetLocalSqlServerInstancesByCallingSqlWmi32()
{
return LocalSqlServerInstancesByCallingSqlWmi(ProviderArchitecture.Use32bit);
}
private static List<string> GetLocalSqlServerInstancesByCallingSqlWmi64()
{
return LocalSqlServerInstancesByCallingSqlWmi(ProviderArchitecture.Use64bit);
}
private static List<string> LocalSqlServerInstancesByCallingSqlWmi(ProviderArchitecture providerArchitecture)
{
try
{
ManagedComputer managedComputer32 = new ManagedComputer();
managedComputer32.ConnectionSettings.ProviderArchitecture = providerArchitecture;
const string defaultSqlInstanceName = "MSSQLSERVER";
return managedComputer32.ServerInstances.Cast<ServerInstance>()
.Select(v =>
(string.IsNullOrEmpty(v.Name) || string.Equals(v.Name, defaultSqlInstanceName, StringComparison.OrdinalIgnoreCase)) ?
v.Parent.Name : string.Format("{0}\\{1}", v.Parent.Name, v.Name))
.OrderBy(v => v, StringComparer.OrdinalIgnoreCase)
.ToList();
}
catch (SmoException ex)
{
Console.WriteLine(ex.Message);
return new List<string>();
}
catch (Exception ex)
{
Console.WriteLine(ex);
return new List<string>();
}
}
private static List<string> GetLocalSqlServerInstancesByReadingRegInstalledInstances()
{
try
{
// HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\InstalledInstances
string[] instances = null;
using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\Microsoft SQL Server"))
{
if (rk != null)
{
instances = (string[])rk.GetValue("InstalledInstances");
}
instances = instances ?? new string[] { };
}
return GetLocalSqlServerInstances(instances);
}
catch (Exception ex)
{
Console.WriteLine(ex);
return new List<string>();
}
}
private static List<string> GetLocalSqlServerInstancesByReadingRegInstanceNames()
{
try
{
// HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL
string[] instances = null;
using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL"))
{
if (rk != null)
{
instances = rk.GetValueNames();
}
instances = instances ?? new string[] { };
}
return GetLocalSqlServerInstances(instances);
}
catch (Exception ex)
{
Console.WriteLine(ex);
return new List<string>();
}
}
private static List<string> GetLocalSqlServerInstances(string[] instanceNames)
{
string machineName = Environment.MachineName;
const string defaultSqlInstanceName = "MSSQLSERVER";
return instanceNames
.Select(v =>
(string.IsNullOrEmpty(v) || string.Equals(v, defaultSqlInstanceName, StringComparison.OrdinalIgnoreCase)) ?
machineName : string.Format("{0}\\{1}", machineName, v))
.ToList();
}
private static List<string> GetLocalSqlServerInstancesByCallingSqlCmd()
{
try
{
// SQLCMD -L
int exitCode;
string output;
CaptureConsoleAppOutput("SQLCMD.exe", "-L", 200, out exitCode, out output);
if (exitCode == 0)
{
string machineName = Environment.MachineName;
return output.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries)
.Select(v => v.Trim())
.Where(v => !string.IsNullOrEmpty(v))
.Where(v => string.Equals(v, "(local)", StringComparison.Ordinal) || v.StartsWith(machineName, StringComparison.OrdinalIgnoreCase))
.Select(v => string.Equals(v, "(local)", StringComparison.Ordinal) ? machineName : v)
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
}
return new List<string>();
}
catch (Exception ex)
{
Console.WriteLine(ex);
return new List<string>();
}
}
private static void CaptureConsoleAppOutput(string exeName, string arguments, int timeoutMilliseconds, out int exitCode, out string output)
{
using (Process process = new Process())
{
process.StartInfo.FileName = exeName;
process.StartInfo.Arguments = arguments;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.CreateNoWindow = true;
process.Start();
output = process.StandardOutput.ReadToEnd();
bool exited = process.WaitForExit(timeoutMilliseconds);
if (exited)
{
exitCode = process.ExitCode;
}
else
{
exitCode = -1;
}
}
}
}
}
public static string SetServer()
{
string serverName = #".\SQLEXPRESS";
var serverNameList = SqlHelper.ListLocalSqlInstances();
if (serverNameList != null)
{
foreach (var item in serverNameList)
serverName = #"" + item;
}
return serverName;
}
To get local server names