Get all sections for appname in RegEdit - c#

Regarding the GetSetting() function in .NET, i have found the GetAllSettings(). That is, GetAllSettings("MyApp", "MySection") will give me all keys under "MySection". I can't, how ever, find anything for getting all sections for my App. In the case above, i would like to get "MySection" as an result for searching "MyApp".
Any ideas?

Try this (C#):
var regKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\MyApp",
RegistryKeyPermissionCheck.ReadSubTree));
var sections = regKey.GetSubKeyNames();
I'm not sure about VB but you may have to use Registry.CurrentUser instead of LocalMachine and then modify the path accordingly (SOFTWARE\MyApp is the path here), based on where your keys are. More info here
Here's the corresponding code for VB.Net - taken from here
Dim rkTest As RegistryKey = Registry.CurrentUser.OpenSubKey("RegistryOpenSubKeyExample")
Console.WriteLine("There are {0} subkeys under Test9999.", _
rkTest.SubKeyCount.ToString())
For Each subKeyName As String In rkTest.GetSubKeyNames()
Dim tempKey As RegistryKey = _
rkTest.OpenSubKey(subKeyName)
Console.WriteLine(vbCrLf & "There are {0} values for " & _
"{1}.", tempKey.ValueCount.ToString(), tempKey.Name)
For Each valueName As String In tempKey.GetValueNames()
Console.WriteLine("{0,-8}: {1}", valueName, _
tempKey.GetValue(valueName).ToString())
Next
Next
This code should work, just make sure your path etc. is being set properly. Or if you can post a screenshot of your registry hives, I can guide you better.

Related

Display string after certain words are found

Basically what I'm trying to do is find the first string that starts with "/Game/Mods" but the problem is how do i tell the program where to end the string? here's an example what a string can look like: string example
As you can see the string starts with "/Game/Mods", i want it to end after the word "TamingSedative", the problem is that the ending word (TamingSedative)is different for every file it has to check, for example: example 2
There you can see that the ending word is now "WeapObsidianSword" (instead of TamingSedative) so basically the string has to end when it comes across the "NUL" but how do i specify that in c# code?
This a simple example using Regex.
Dim yourString As String = "/Game/Mods/TamingSedative/PrimalItemConsumable_TamingSedative"
Dim M As System.Text.RegularExpressions.Match = System.Text.RegularExpressions.Regex.Match(yourString, "/Game/Mods/(.+?)/")
MessageBox.Show(M.Groups(0).Value) 'This should show /Game/Mods/TamingSedative/
MessageBox.Show(M.Groups(1).Value) 'This should show TamingSedative
Since you need only the first occurance, this is the simplest solution I could think of:
(In case you cannot see the image, click on it to open in new tab)
EDIT:
In case the existence of a path like this is not guaranteed in the string, you can do an additional check before proceeding to use Substring, like this:
int exists = fullString.IndexOf("/Game/Mods");
if (exists == -1) return null;
Note: I have included "ENDED" in order to see in case any NULL chars have been included (white spaces)
From your comments: "the string just has to start at /Game/Mods and end when it reaches the whitespace".
In that case, you can easily get the matches using Linq, like this (assuming filePath is a string that has the path to your file):
var text = File.ReadAllText(filePath);
var matches = text.Split(null).Where(s => s.StartsWith("/Game/Mods"));
And, if you only need the first occurrence, it would be:
var firstMatch = matches.Any() ? matches.First() : null;
Check this post.

The use of Lastindexof and Remove in C# for database confusion

Ok iv tried everything i cant get this to work it shows me nothing:
foreach (DataRow dr in dt.Rows)
{
keyNameTextBox.Text = dr["KeyName"].ToString().Remove(keyNameTextBox.Text.LastIndexOf("_") + 1); ;
keyTextBox.Text = dr["Key"].ToString();
}
if I change after .Remove (0
it then gives me the result which is good but only everything after _
But My goal is to see everything before _ excluding the _
Iv seen a Stack Overflow posts which helped me find out about indexof and remove but for some reason both not working for me is it because im in a for each ? how would i get around it ? any help would be awesome!
Source i used:
Remove characters after specific character in string, then remove substring?
Here
dr["KeyName"].ToString().Remove(keyNameTextBox.Text.LastIndexOf("_") + 1);
you search in one string (keyNameTextBox.Text) and remove from another (dr["KeyName"].ToString()).
What you really need is something like this:
var keyName = dr["KeyName"].ToString();
keyNameTextBox.Text = keyName.Remove(keyName.LastIndexOf("_") + 1);

Copy specific folders to new location

Firs of, i am new here and hope you can help.
I am a systen engeneer and have to move (copy) 400 out of 500 folder's in a directory.
The folder names are uniek GUID {f199a57f-fbee-411b-a70e-32619f87e6aa} naming
Is there a VB or C# way to have the user input the 400 names of the folders that need to be copyd and let the scrip search them and copy the folders too a new location?
Thank you for your help...
Regards,
Wim
Wat i tried:
I tried this, but noting hapens :-(
Sub CopySomeFolder()
Dim FSO, sourceFolder, currentFile, filesInSourceFolder
Dim strSourceFolderPath
Dim strDestinationFolderPath
Dim strUserInput
Set FSO = CreateObject("Scripting.FileSystemObject")
' Figure out which folder to copy from where to where
strUserInput = InputBox("Please enter name of file to copy.")
strSourceFolderPath = "M:\"
strDestinationFolderPath = "M:\"
Set sourceFolder = FSO.GetFolder(strSourceFolderPath)
Set filesInSourceFolder = sourceFolder.Files
' Look at all folders in source folder. If name matches,
' copy to destination folder.
For Each currentFile In filesInSourceFolder
If currentFile.Name = strUserInput Then
currentFile.Copy (FSO.BuildPath(strDestinationFolderPath, _
currentFile.Name))
End If
Next
End Sub
Decide whether you need to copy folders or files
Don't be a sadist - asking a user to type 400 GUIDs into an InputBox!
Use dir to create the list of all 500 folder in a text file
Ask your asistent to delete the 100 not to be copied
Use a .bat or .vbs to copy the 400 remaining folders
This is simple to do. Example script that will read a text file and move them is as fallows;
Const ForReading = 1
Const list = "c:\list_of_folders.txt"
Const destination = "c:\temp\"
Dim fso : Set fso = CreateObject("Scripting.FileSystemObject")
Dim folders : Set folders = fso.OpenTextFile(list, ForReading)
Dim folder
Do Until folders.AtEndOfStream
folder_loc = folders.ReadLine
If fso.FolderExists(folder_loc) Then
Set folder = fso.GetFolder(folder_loc)
folder.move(destination)
End If
Loop
Wscript.echo "Operation completed."
The list_of_folders.txt needs to have full paths.
First of, thank's for all your help...
We ended up using both answers. We got the DB admins to give us the GUIS's that have to be moved, slapt that in too 4 txt doc's, 1 for everyday of the migration. We used copy, not move for if something goes wrong.... here is the script i made...
Dim arrFileLines()
i = 0
set filesys = CreateObject("Scripting.FileSystemObject")
Set objFSO = CreateObject("Scripting.FileSystemObject")
strUserInput = InputBox ("Pathe to TXT file containing the folder names: " & _
chr(10) & chr(10) & "(i.e. C:\Program Files or " & _
"\\Servername\C$\Program Files)")
strUserInputFrom = InputBox("Enter the directory path to the folders u want to copy: " & _
chr(10) & chr(10) & "(i.e. C:\Program Files or " & _
"\\Servername\C$\Program Files)")
strUserInputTo = InputBox("Enter the destination folder: " & _
chr(10) & chr(10) & "(i.e. C:\Program Files or " & _
"\\Servername\C$\Program Files)")
Set objFile = objFSO.OpenTextFile(strUserInput, 1)
Do Until objFile.AtEndOfStream
Redim Preserve arrFileLines(i)
arrFileLines(i) = objFile.ReadLine
i = i + 1
Loop
objFile.Close
For l = Ubound(arrFileLines) to LBound(arrFileLines) Step -1
Wscript.echo strUserInputFrom&"\"&arrFileLines(l) &" copy to " & strUserInputTo&"\"
filesys.CopyFolder strUserInputFrom&"\"&arrFileLines(l), strUserInputTo&"\"
Next
Please let me know if there is a better way, i like to learn :-)
Thanks

Verifying path equality with .Net

What is the best way to compare two paths in .Net to figure out if they point to the same file or directory?
How would one verify that these are the same:
c:\Some Dir\SOME FILE.XXX
C:\\\SOME DIR\some file.xxx
Even better: is there a way to verify that these paths point to the same file on some network drive:
h:\Some File.xxx
\\Some Host\Some Share\Some File.xxx
UPDATE:
Kent Boogaart has answered my first question correctly; but I`m still curious to see if there is a solution to my second question about comparing paths of files and directories on a network drive.
UPDATE 2 (combined answers for my two questions):
Question 1: local and/or network files and directories
c:\Some Dir\SOME FILE.XXX
C:\\\SOME DIR\some file.xxx
Answer: use System.IO.Path.GetFullPath as exemplified with:
var path1 = Path.GetFullPath(#"c:\Some Dir\SOME FILE.XXX");
var path2 = Path.GetFullPath(#"C:\\\SOME DIR\subdir\..\some file.xxx");
// outputs true
Console.WriteLine("{0} == {1} ? {2}", path1, path2, string.Equals(path1, path2, StringComparison.OrdinalIgnoreCase));
Question 2: local and/or network files and directories
Answer: Use the GetPath method as posted on
http://briancaos.wordpress.com/2009/03/05/get-local-path-from-unc-path/
var path1 = Path.GetFullPath(#"c:\Some Dir\SOME FILE.XXX");
var path2 = Path.GetFullPath(#"C:\\\SOME DIR\subdir\..\some file.xxx");
// outputs true
Console.WriteLine("{0} == {1} ? {2}", path1, path2, string.Equals(path1, path2, StringComparison.OrdinalIgnoreCase));
Ignoring case is only a good idea on Windows. You can use FileInfo.FullName in a similar fashion, but Path will work with both files and directories.
Not sure about your second example.
Although it's an old thread posting as i found one.
Using Path.GetFullpath I could solve my Issue
eg.
Path.GetFullPath(path1).Equals(Path.GetFullPath(path2))
Nice syntax with the use of extension methods
You can have a nice syntax like this:
string path1 = #"c:\Some Dir\SOME FILE.XXX";
string path2 = #"C:\\\SOME DIR\subdir\..\some file.xxx";
bool equals = path1.PathEquals(path2); // true
With the implementation of an extension method:
public static class StringExtensions {
public static bool PathEquals(this string path1, string path2) {
return Path.GetFullPath(path1)
.Equals(Path.GetFullPath(path2), StringComparison.InvariantCultureIgnoreCase);
}
}
Thanks to Kent Boogaart for the nice example paths.
I had this problem too, but I tried a different approach, using the Uri class. I found it to be very promising so far :)
var sourceUri = new Uri(sourcePath);
var targetUri = new Uri(targetPath);
if (string.Compare(sourceUri.AbsoluteUri, targetUri.AbsoluteUri, StringComparison.InvariantCultureIgnoreCase) != 0
|| string.Compare(sourceUri.Host, targetUri.Host, StringComparison.InvariantCultureIgnoreCase) != 0)
{
// this block evaluates if the source path and target path are NOT equal
}
As reported by others, Path.GetFullPath or FileInfo.FullName provide normalized versions of local files. Normalizing a UNC path for comparison is quite a bit more involved but, thankfully, Brian Pedersen has posted a handy MRU (Method Ready to Use) to do exactly what you need on his blog, aptly titled Get local path from UNC path. Once you add this to your code, you then have a static GetPath method that takes a UNC path as its sole argument and normalizes it to a local path. I gave it a quick try and it works as advertised.
A very simple approach I use to determine if two path strings point to the same location is to create a temp file in Path1 and see if it shows up in Path2. It is limited to locations you have write-access to, but if you can live with that, it’s easy! Here’s my VB.NET code (which can easily be converted to C#) …
Public Function SamePath(Path1 As String, Path2 As String) As String
' Returns: "T" if Path1 and Path2 are the same,
' "F" if they are not, or
' Error Message Text
Try
Path1 = Path.Combine(Path1, Now.Ticks.ToString & ".~")
Path2 = Path.Combine(Path2, Path.GetFileName(Path1))
File.Create(Path1).Close
If File.Exists(Path2) Then
Path2 = "T"
Else
Path2 = "F"
End If
File.Delete(Path1)
Catch ex As Exception
Path2 = ex.Message
End Try
Return Path2
End Function
I return the result as a string so I can provide an error message if the user enters some garbage. I’m also using Now.Ticks as a “guaranteed” unique file name but there are other ways, like Guid.NewGuid.
you can use FileInfo!
string Path_test_1="c:\\main.h";
string Path_test_2="c:\\\\main.h";
var path1=new FileInfo(Path_test_1)
var path2=new FileInfo(Path_test_2)
if(path1.FullName==path2.FullName){
//two path equals
}
Only one way to ensure that two paths references the same file is to open and compare files. At least you can instantiate FileInfo object and compare properties like:
CreationTime, FullName, Size, etc. In some approximation it gives you a guarantee that two paths references the same file.
Why not create a hash of each file and compare them? If they are the same, you can be reasonably sure they are the same file.

Regex: absolute url to relative url (C#)

I need a regex to run against strings like the one below that will convert absolute paths to relative paths under certain conditions.
<p>This website is <strong>really great</strong> and people love it <img alt="" src="http://localhost:1379/Content/js/fckeditor/editor/images/smiley/msn/teeth_smile.gif" /></p>
Rules:
If the url contains "/Content/" I
would like to get the relative path
If the url does not contain
"/Content/", it is an external file,
and the absolute path should remain
Regex unfortunatley is not my forte, and this is too advanced for me at this point. If anyone can offer some tips I'd appreciate it.
Thanks in advance.
UPDATE:
To answer questions in the comments:
At the time the Regex is applied, All urls will begin with "http://"
This should be applied to the src attribute of both img and a tags, not to text outside of tags.
You should consider using the Uri.MakeRelativeUri method - your current algorithm depends on external files never containing "/Content/" in their path, which seems risky to me. MakeRelativeUri will determine whether a relative path can be made from the current Uri to the src or href regardless of changes you or the external file store make down the road.
Unless I'm missing the point here, if you replace
^(.*)([C|c]ontent.*)
With
/$2
You will end up with
/Content/js/fckeditor/editor/images/smiley/msn/teeth_smile.gif
This will only happen id "content" is found, so in cae you have a URL such as:
http://localhost:1379/js/fckeditor/editor/images/smiley/msn/teeth_smile.gif
Nothing will be replaced
Hope it helps, and that i didn't miss anything.
UPDATE
Obviously considering you are using an HTML parser to find the URL inside the a href (which you should in case you're not :-))
Cheers
That is for perl, I do not know c#:
s#(<(img|a)\s[^>]*?\s(src|href)=)(["'])http://[^'"]*?(/Content/[^'"]*?)\4#$1$4$5#g
If c# has perl-like regex it will be easy to port.
This function can convert all the hyperlinks and image sources inside your HTML to absolute URLs and for sure you can modify it also for CSS files and Javascript files easily:
Private Function ConvertALLrelativeLinksToAbsoluteUri(ByVal html As String, ByVal PageURL As String)
Dim result As String = Nothing
' Getting all Href
Dim opt As New RegexOptions
Dim XpHref As New Regex("(href="".*?"")", RegexOptions.IgnoreCase)
Dim i As Integer
Dim NewSTR As String = html
For i = 0 To XpHref.Matches(html).Count - 1
Application.DoEvents()
Dim Oldurl As String = Nothing
Dim OldHREF As String = Nothing
Dim MainURL As New Uri(PageURL)
OldHREF = XpHref.Matches(html).Item(i).Value
Oldurl = OldHREF.Replace("href=", "").Replace("HREF=", "").Replace("""", "")
Dim NEWURL As New Uri(MainURL, Oldurl)
Dim NewHREF As String = "href=""" & NEWURL.AbsoluteUri & """"
NewSTR = NewSTR.Replace(OldHREF, NewHREF)
Next
html = NewSTR
Dim XpSRC As New Regex("(src="".*?"")", RegexOptions.IgnoreCase)
For i = 0 To XpSRC.Matches(html).Count - 1
Application.DoEvents()
Dim Oldurl As String = Nothing
Dim OldHREF As String = Nothing
Dim MainURL As New Uri(PageURL)
OldHREF = XpSRC.Matches(html).Item(i).Value
Oldurl = OldHREF.Replace("src=", "").Replace("src=", "").Replace("""", "")
Dim NEWURL As New Uri(MainURL, Oldurl)
Dim NewHREF As String = "src=""" & NEWURL.AbsoluteUri & """"
NewSTR = NewSTR.Replace(OldHREF, NewHREF)
Next
Return NewSTR
End Function

Categories