When trying to open a Linear Programming problem from text with Gurobi+C# it throws the error: 10012 Unable to open file "Maximize" for input.
Maximise is the first word of the text and when using
foreach (string s in args)
{
Console.WriteLine(s);
}
i get the correct output from the text file. Please help!
using System;
using Gurobi;
class lp_cs
{
static void Main(string[] args)
{
args = System.IO.File.ReadAllLines(#"C:\Users\Ben\Documents\Visual Studio 2015\Projects\ConsoleApplication5\ConsoleApplication5\mps.lp");
foreach (string s in args)
{
Console.WriteLine(s);
}
if (args.Length < 1)
{
Console.Out.WriteLine("Please Wait..");
return;
}
try
{
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env, args[0]);
model.Optimize();
int optimstatus = model.Get(GRB.IntAttr.Status);
if (optimstatus == GRB.Status.INF_OR_UNBD)
{
model.GetEnv().Set(GRB.IntParam.Presolve, 0);
model.Optimize();
optimstatus = model.Get(GRB.IntAttr.Status);
}
if (optimstatus == GRB.Status.OPTIMAL)
{
double objval = model.Get(GRB.DoubleAttr.ObjVal);
Console.WriteLine("Optimal objective: " + objval);
}
else if (optimstatus == GRB.Status.INFEASIBLE)
{
Console.WriteLine("Model is infeasible");
model.ComputeIIS();
model.Write("model.ilp");
}
else if (optimstatus == GRB.Status.UNBOUNDED)
{
Console.WriteLine("Model is unbounded");
}
else
{
Console.WriteLine("Optimization was stopped with status = "
+ optimstatus);
}
model.Dispose();
env.Dispose();
}
catch (GRBException e)
{
Console.WriteLine("Hibakód: " + e.ErrorCode + ". " + e.Message);
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}
With
args = System.IO.File.ReadAllLines(#"C:\Users\Ben\Documents\Visual Studio 2015\Projects\ConsoleApplication5\ConsoleApplication5\mps.lp");
you are overwriting the args parameter of your main() method with an array of all lines of the input file. That's why in
GRBModel model = new GRBModel(env, args[0]);
args[0] contains a string with the first line of your LP file instead of the filename.
Related
So, I've written a program which takes data from an file and process it and presents the answer. I got an error that's a bit confusing. If I call the program in the command prompt as follows: test.exe < indata.txt nothing happens, if I skip the < i.e. calls the program as: test.txt indata.txt it works fine. It also works if I call it with double in data files. Like: test.txt < indata.txt indata.txt. It's like the < token skips the following entry.
static void Main(string[] args)
{
int revolter = 0;
string[] buffer_array = new string[2000];
string path = "./";
if (args.Length == 0)
{
string read_string = System.Console.ReadLine();
buffer_array = read_string.Split(' ');
}
else
{
path += args[0];
System.Console.WriteLine(path);
StreamReader read_string = File.OpenText(path);
string s = read_string.ReadToEnd();
buffer_array = s.Split('\n');
}
}
Edit: spelling
The following shows how to create a Console program that reads data from a filename that's been specified by one of the following:
redirecting input (< infile.txt)
specifying the filename using an argument (-f:<filename> or -f:"<filename containing spaces>")
prompting the user for a filename if the filename wasn't specified
For usage, run the program with /? as the only argument.
static void Main(string[] args)
{
string filename = string.Empty;
string[] buffer = null;
if (Console.IsInputRedirected)
{
string data = Console.In.ReadToEnd();
//Console.WriteLine(data);
//set value
buffer = data.Split('\n');
}
else if (args != null && args.Length > 0)
{
foreach (var arg in args)
{
//Console.WriteLine("arg: " + arg);
if (arg == "/?")
{
Usage();
}
else if (arg.StartsWith("-f"))
{
//Console.WriteLine("arg: '" + arg + "'");
//set value
filename = arg.Substring(3).Trim();
if (!String.IsNullOrEmpty(filename))
{
if (!System.IO.File.Exists(filename))
{
Console.Error.WriteLine("Error: File '" + filename + "' doesn't exist.");
//return;
}
else
{
//read data
buffer = System.IO.File.ReadAllLines(filename);
}
}
else
{
Console.Error.WriteLine("Error: '-f' was specified, but filename wasn't specified (Note: No space is allowed between '-f:' and <filename>)");
//return;
}
}
else
{
Console.Error.WriteLine("Error: Argument '" + arg + "' unknown");
Usage();
}
}
}
else
{
do
{
Console.Write("Please enter filename ('q' to quit): ");
filename = Console.ReadLine();
//remove double quotes
filename = filename.Replace("\"", "");
if (filename == "Q" || filename == "q")
{
return;
}
else if (!System.IO.File.Exists(filename))
{
Console.Error.WriteLine("Error: File '" + filename + "' doesn't exist.");
}
else
{
//read data
buffer = System.IO.File.ReadAllLines(filename);
break;
}
} while (true);
}
//display data
DisplayData(buffer);
}
static void DisplayData(string[] buffer)
{
if (buffer != null)
{
foreach (string val in buffer)
{
Console.WriteLine(val);
}
}
}
static void Usage()
{
StringBuilder sb = new StringBuilder();
//string exeName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
string exeName = System.AppDomain.CurrentDomain.FriendlyName;
sb.AppendFormat("{0}Usage:{0}", System.Environment.NewLine);
sb.AppendFormat("{0} -f:C:\\Temp\\Test1.txt{1}", exeName, System.Environment.NewLine);
sb.AppendFormat("{0} -f:\"C:\\Temp\\Test 2.txt\"{1}", exeName, System.Environment.NewLine);
Console.Write(sb.ToString());
}
If the program is going to be called as you described (using the < filename.txt command line), the contents of the file will be available on STDIN. Your code is what you would do if your program would be called with the filename as an argument.
You can use code like this to handle text on STDIN:
using System;
using System.IO;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
TextReader input = Console.In;
String inpText = input.ReadToEnd();
foreach(String line in inpText.Split('\n')) {
Console.WriteLine("+++" + line);
}
}
}
}
For an input like this:
This
Is
A
Multiline
Text File
Using ConsoleApp1.exe < input.txt you get:
+++This
+++Is
+++A
+++Multiline
+++Text File
+++
(Newer to C#)
I have an application that I have built that copies files and folders from one location to another. I originally had issues with folders. For some reason, it would try to copy the file over without creating the directory. I solved that by adding a second section to check if the folder exists and if not create it. I am sure there is a better way to handle this, but this is what worked, so I went with it. The ultimate goal is this.
check if the file/folder exists in the destination location and is older than the source file/folder
If the file/folder doesn't exist, copy it over. If the file/folder is older than the source, copy it over.
If the file folder exists in the destination and not in the source (indicating it was deleted) move the file from the destination location to an archive folder
Below is what I have so far, and it does everything but what is described in #3 above. Any ideas in regards to how I can add the ability from #3 into the functionality, or simplify the copy of files and create the folder if it doesn't exist would be much appreciated.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FileCopy
{
class Program
{
public static string dtnow = DateTime.Now.ToString("mmdd_hhmm");
public static string watch_path = string.Empty;
public static string copy_path = string.Empty;
public static string final_copy_path = string.Empty;
public static string log_folder = #"C:\copylogs";
//public static string log_file = "copy_log";
public static string log_file = Path.Combine(log_folder + "\\copy_log" + dtnow + ".txt");
public static int newer_count = 0;
public static int skip_count = 0;
public static int copy_count = 0;
public static int totalcount = 0;
public static int currentcount = 0;
static void Main(string[] args)
{
if (args == null || args.Length < 2)
{
Console.WriteLine("Invalid Syntax");
return;
}
else
{
watch_path = args[0];
copy_path = args[1];
log_start_Check(log_folder,log_file);
CopyFolder(watch_path, copy_path);
finalcount_statement();
}
}
// Log Folder check and creation
public static void log_start_Check(string log_folder, string log_file)
{
Console.Write("Checking Log Folder: ");
if (!Directory.Exists(log_folder))
{
try
{
Directory.CreateDirectory(log_folder);
Console.WriteLine("Created!");
}
catch (Exception error)
{
Console.WriteLine("Unable to Create Directory" + error);
return;
}
}
else
{
Console.WriteLine("Exists");
}
Console.Write("Checking Log File: ");
//Console.WriteLine(log_file);
if (!File.Exists(log_file))
{
try
{
File.Create(log_file);
Console.WriteLine("Created!");
}
catch (Exception error)
{
Console.WriteLine("Unable to Create file" + error);
return;
}
}
else
{
Console.WriteLine("Exists");
}
Console.WriteLine();
}
// Copy Folder Functions
static public void CopyFolder(string sourceFolder, string destFolder)
{
try
{
if (!Directory.Exists(destFolder))
Directory.CreateDirectory(destFolder);
totalcount = Directory.GetFiles(sourceFolder, "*.*", SearchOption.AllDirectories).Count();
string[] files = Directory.GetFiles(sourceFolder);
totalcount = files.Length;
foreach (string file in files)
{
string name = Path.GetFileName(file);
FileInfo source_info = new FileInfo(file);
string dest = Path.Combine(destFolder, name);
FileInfo dest_info = new FileInfo(dest);
if (File.Exists(dest))
{
try
{
if (source_info.LastWriteTime > dest_info.LastWriteTime)
{
//Console.Write("\r" + currentcount + " of " + totalcount + " Completed ");
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Yellow;
File.Copy(file, dest, true);
Console.Write("\rFile Newer, File Copied " + dest + " ");
Console.ResetColor();
newer_count++;
}
else
{
//Console.Write("\r" + currentcount + " of " + totalcount + " Completed ");
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("\r** - File Exists " + dest + " ");
Console.ResetColor();
skip_count++;
}
}
catch (Exception error)
{
error_handling("Error in Application " + error.Message, dest, file);
}
}
else
{
try
{
//Console.Write("\r"+currentcount + " of " + totalcount + " Completed ");
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Green;
File.Copy(file, dest, false);
Console.Write("\rFile Copied " + dest + " ");
Console.ResetColor();
copy_count++;
}
catch (Exception error)
{
error_handling("Error in Application " + error.Message, dest, file);
}
}
currentcount++;
}
string[] folders = Directory.GetDirectories(sourceFolder);
foreach (string folder in folders)
{
string name = Path.GetFileName(folder);
string dest = Path.Combine(destFolder, name);
CopyFolder(folder, dest);
}
}
catch (Exception error)
{
error_handling("Error in Application " + error.Message, null, null);
}
}
// Error Handling to add messages to logs
public static void error_handling(string message, string fileident, string source)
{
using (System.IO.StreamWriter myFile = new System.IO.StreamWriter(log_file, true))
{
string finalMessage = string.Format("{0}: {1} SOURCE: {3} - DEST: {2}", DateTime.Now, message, fileident, source, Environment.NewLine);
myFile.WriteLine(finalMessage);
myFile.Close();
}
}
// Final Statement
public static void finalcount_statement()
{
Console.WriteLine("");
Console.WriteLine("--------------------------------------------------------------------------------------------");
Console.WriteLine("Total New Files Copied: " + copy_count);
Console.WriteLine("Total Newer Files Updated: " + newer_count);
Console.WriteLine("Total Files Skipped: " + skip_count);
Console.WriteLine("--------------------------------------------------------------------------------------------");
Console.WriteLine("");
Console.WriteLine("");
}
}
}
You can do it the same way around, maybe like this:
static public void ArchiveCopyFolder(string sourceFolder, string destFolder)
{
try
{
if (!Directory.Exists(sourceFolder))
{
Directory.CreateDirectory(archivefolder + destFolder);
//Copy folder and files
}
}
}
I'm working on a project where I'll have a C# application search all TFS project's .cs files for a string or string patterns. I found some code that looks similar to what I was looking to do here.
namespace TFSSearch
{
class Program
{
static string[] textPatterns = new[] { "void main(", "exception", "RegisterScript" }; //Text to search
static string[] filePatterns = new[] { "*.cs", "*.xml", "*.config", "*.asp", "*.aspx", "*.js", "*.htm", "*.html",
"*.vb", "*.asax", "*.ashx", "*.asmx", "*.ascx", "*.master", "*.svc"}; //file extensions
static void Main(string[] args)
{
try
{
var tfs = TfsTeamProjectCollectionFactory
.GetTeamProjectCollection(new Uri("https://{tfsserver}/tfs"));
tfs.EnsureAuthenticated();
var versionControl = tfs.GetService<VersionControlServer>();
StreamWriter outputFile = new StreamWriter(#"C:\Find.txt");
var allProjs = versionControl.GetAllTeamProjects(true);
foreach (var teamProj in allProjs)
{
foreach (var filePattern in filePatterns)
{
var items = versionControl.GetItems(teamProj.ServerItem + "/" + filePattern, RecursionType.Full).Items
.Where(i => !i.ServerItem.Contains("_ReSharper")); //skipping resharper stuff
foreach (var item in items)
{
List<string> lines = SearchInFile(item);
if (lines.Count > 0)
{
outputFile.WriteLine("FILE:" + item.ServerItem);
outputFile.WriteLine(lines.Count.ToString() + " occurence(s) found.");
outputFile.WriteLine();
}
foreach (string line in lines)
{
outputFile.WriteLine(line);
}
if (lines.Count > 0)
{
outputFile.WriteLine();
}
}
}
outputFile.Flush();
}
}
catch (Exception e)
{
string ex = e.Message;
Console.WriteLine("!!EXCEPTION: " + e.Message);
Console.WriteLine("Continuing... ");
}
Console.WriteLine("========");
Console.Read();
}
// Define other methods and classes here
private static List<string> SearchInFile(Item file)
{
var result = new List<string>();
try
{
var stream = new StreamReader(file.DownloadFile(), Encoding.Default);
var line = stream.ReadLine();
var lineIndex = 0;
while (!stream.EndOfStream)
{
if (textPatterns.Any(p => line.IndexOf(p, StringComparison.OrdinalIgnoreCase) >= 0))
result.Add("=== Line " + lineIndex + ": " + line.Trim());
line = stream.ReadLine();
lineIndex++;
}
}
catch (Exception e)
{
string ex = e.Message;
Console.WriteLine("!!EXCEPTION: " + e.Message);
Console.WriteLine("Continuing... ");
}
return result;
}
}
}
The problem I'm having is when I try to get the projects using versionControl.GetAllTeamProjects(true); allProjs seems to get no information back. It is an empty array of TeamProject. When I debug, tfs.HasAuthenticated is true and it doesn't throw any exceptions. The TFS server is on a https domain. How can I make sure I'm exactly connecting to TFS?
I test at my side, everything works correctly.
Install the Nuget package
Microsoft.TeamFoundationServer.ExtendedClient by running below
command in Package Manager Console:
PM> Install-Package Microsoft.TeamFoundationServer.ExtendedClient -Version 15.112.1
Make sure you specify the correct TFS server,
eg : http://servername:8080/tfs/DefaultCollection
Then check it again.
I have a program that converts .ppt or pptx files to png's using C# and the Microsoft.Office.Interop stuff.
It works most of the time, but under certain circumstances, it seems to fail on specific filenames for some nondescript reason.
HRESULT E_FAIL at ... Presentations.Open
It'll fail on CT_Stress_Test - Copy (16).pptx and CT_Stress_Test - Copy (11).pptx It works for (2) thru (19), but fails on only these two. My question is why?
If I were to make copies of these copies, or rename them to something else, it'll convert just fine, so I think it might have something to do with the filename.
I have the same conversion program running on my server and my local machine. My local machine (Win 7) converts the problem files just file. It's only on the server (Win 2008) that I have problems with these two filenames.
EDIT: I've found another number that doesn't work: (38)
EDIT: I formatted the strings with Path functions, and that didn't help.
EDIT: I was able to fix it by trimming all the spaces from the file names. I still want to know why this happens, though.
Here's the program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.IO;
using Microsoft.Office.Core;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using System.Diagnostics;
using System.Timers;
using System.Security.Permissions;
using System.Collections.Concurrent;
namespace converter
{
class Program
{
public static int threadLimit=0;
public static string inDir;
public static string outDir;
public static string procDir;
public static Thread[] converterThreads;
public static BlockingCollection<string> todo;
static void Main(string[] args)
{
todo = new BlockingCollection<string>();
inDir = args[0];
outDir = args[1]+"\\";
procDir = args[2]+"\\";
Int32.TryParse(args[3],out threadLimit);
converterThreads = new Thread[threadLimit];
FileSystemWatcher watcher = new FileSystemWatcher(inDir); //Watcher "thread"
watcher.Filter = "*.ppt*";
watcher.NotifyFilter = watcher.NotifyFilter | NotifyFilters.CreationTime;
watcher.IncludeSubdirectories = false;
watcher.Created += new FileSystemEventHandler(fileChanged);
watcher.EnableRaisingEvents = true;
//Create consumer threads
for(var i=0;i<threadLimit;i++)
{
Conversion con = new Conversion();
converterThreads[i] = new Thread(new ThreadStart(con.watchCollection));
converterThreads[i].Start();
}
//stay open
Console.ReadLine();
}
//Producer
private static void fileChanged(object sender, FileSystemEventArgs e)
{
if(!(e.FullPath.Contains("~$"))){ //Ignore temp files
Console.WriteLine("found =" + e.FullPath);
todo.Add(e.FullPath);
}
}
}
class Logger{
static void toLog(String msg)
{
//TODO: log file
}
}
//Consumer
class Conversion
{
String input;
String output;
String outDir;
String process;
String nameWith;
String nameWithout;
string dir;
static List<CorruptFile> cFiles = new List<CorruptFile>();
int retryLimit = 20;
public Conversion()
{
this.outDir = Program.outDir;
this.process = Program.procDir;
}
//Continually watches collection for files to take.
public void watchCollection()
{
while (true)
{
System.Threading.Thread.Sleep(1000);
try
{
dir = Program.todo.Take();
if (dir != null)
{
this.nameWithout = Path.GetFileNameWithoutExtension(dir);
this.nameWith = Path.GetFileName(dir);
this.output = Path.GetDirectoryName(dir) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(dir);
Console.WriteLine("output = " + this.output);
this.input = Path.GetFullPath(dir);
Console.WriteLine("thread took " + this.nameWith);
convertPpt();
}
}
catch (InvalidOperationException) { }
}
}
public void convertPpt()
{
try
{
var app = new PowerPoint.Application();
var pres = app.Presentations;
var file = pres.Open(input, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse);
file.SaveAs(output, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPNG, MsoTriState.msoTrue);
file.Close();
app.Quit();
Console.WriteLine("file converted " + input);
moveFile();
}
catch (Exception e)
{
Console.WriteLine("convertPpt failed " + e);
try
{
foreach (Process proc in Process.GetProcessesByName("POWERPNT"))
{
proc.Kill();
Console.WriteLine("process killed");
}
}
catch (Exception e3)
{
}
try
{
if (!(cFiles.Any(x => x.fileName == dir)))
{
cFiles.Add(new CorruptFile(dir));
Console.WriteLine("file added to watch list");
Program.todo.Add(dir);
}
else
{
var found = cFiles.Find(x => x.fileName == dir);
Console.WriteLine("in watch list = " + found.fileName);
if (found.numRetry >= retryLimit)
{
Console.WriteLine(nameWith+ " to be ignored");
try
{
cFiles.Remove(found);
Console.WriteLine("File ignored");
System.Threading.Thread.Sleep(300);
Console.WriteLine("Moving: " + input);
if (File.Exists("C:\\corrupt\\" + nameWith))
{
File.Replace(input, "C:\\corrupt\\" + nameWith, null);
Console.WriteLine("file moved to C:\\corrupt\\");
}
else
{
File.Move(input, "C:\\corrupt\\" + nameWith);
Console.WriteLine("file moved to C:\\corrupt\\");
}
}
catch(Exception e5)
{
Console.WriteLine("could not move file " + e5);
}
}
else
{
Console.WriteLine("retrying file on watch list");
found.numRetry++;
Program.todo.Add(dir);
}
}
}
catch { }
}
moveDir();
}
public void moveFile()
{
Console.WriteLine("moving" + input);
try
{
System.Threading.Thread.Sleep(500);
Console.WriteLine(string.Format("moving {0} to {1}", input, process + nameWith));
if (File.Exists(process + nameWith))
{
File.Replace(input, process + nameWith, null);
}
else
{
File.Move(input, process + nameWith);
}
}
catch (Exception e)
{
Console.WriteLine(string.Format("Unable to move the file {0} ", input) + e);
try
{
foreach (Process proc in Process.GetProcessesByName("POWERPNT"))
{
proc.Kill();
}
}
catch (Exception e3)
{
}
}
}
public void moveDir()
{
if(!Directory.Exists(output)){
return;
}
Console.WriteLine("moving dir " + output);
try
{
Console.WriteLine(string.Format("moving dir {0} to {1} ", output, outDir + nameWithout));
if (Directory.Exists(outDir + nameWithout))
{
Directory.Delete(outDir + nameWithout, true);
}
if (Directory.Exists(output))
{
Directory.Move(output, outDir + nameWithout);
}
}
catch (Exception e)
{
Console.WriteLine(string.Format("Unable to move the directory {0} ", output) + e);
try
{
foreach (Process proc in Process.GetProcessesByName("POWERPNT"))
{
proc.Kill();
}
}
catch (Exception e3)
{
}
}
}
}
class CorruptFile{
public string fileName;
public int numRetry;
public CorruptFile(string fn){
fileName = fn;
}
}
}
First up is a warning from Microsoft in this KB article here. Money quote is:
Microsoft does not currently recommend, and does not support,
Automation of Microsoft Office applications from any unattended,
non-interactive client application or component (including ASP,
ASP.NET, DCOM, and NT Services), because Office may exhibit unstable
behaviour and/or deadlock when Office is run in this environment.
Next question is why not use OpenXML for this? Here's a simple sample to get you started which counts the number of slides in a deck.
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Packaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace OpenXmlDemo
{
class PptOpenXmlDemo
{
public int PptGetSlideCount(string fileName)
{
// Return the number of slides in a PowerPoint document.
const string documentRelationshipType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument";
const string presentationmlNamespace = "http://schemas.openxmlformats.org/presentationml/2006/main";
int returnValue = 0;
using (Package pptPackage = Package.Open(fileName, FileMode.Open, FileAccess.Read))
{
// Get the main document part (presentation.xml).
foreach (System.IO.Packaging.PackageRelationship relationship in pptPackage.GetRelationshipsByType(documentRelationshipType))
{
// There should be only a single relationship that refers to the document.
Uri documentUri = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), relationship.TargetUri);
PackagePart documentPart = pptPackage.GetPart(documentUri);
// Get the slide part from the package.
if (documentPart != null)
{
XmlDocument doc = new XmlDocument();
doc.Load(documentPart.GetStream());
// Manage namespaces to perform XPath queries.
XmlNamespaceManager nsManager = new XmlNamespaceManager(doc.NameTable);
nsManager.AddNamespace("p", presentationmlNamespace);
// Retrieve the list of slide references from the document.
XmlNodeList nodes = doc.SelectNodes("//p:sldId", nsManager);
if (nodes != null)
{
returnValue = nodes.Count;
}
}
// There is only one officeDocument part. Get out of the loop now.
break;
}
}
return returnValue;
}
}
}
These codes allow me to access the registry and grab out the lastvisitedMRU values which are in a non-readable format. What I did here was to convert them into a readable format. I placed them in an array and output them into console.
The output goes like this:
C : \ P r o g r a m F i l e s \ i P o d \ f i l e . t x t
How do I remove the spacings in between?
Thanks in advance.
try
{
RegistryKey rk = Registry.CurrentUser;
rk = rk.OpenSubKey(#"Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32\LastVisitedMRU", false);
PrintKeys(rk);
}
catch (Exception MyError)
{
Console.WriteLine("An error has occurred: " + MyError.Message);
}
}
static void PrintKeys(RegistryKey rk)
{
if (rk == null)
{
Console.WriteLine("No specified registry key!");
return;
}
String[] names = rk.GetValueNames();
Console.WriteLine("Subkeys of " + rk.Name);
Console.WriteLine("-----------------------------------------------");
foreach (String s in names)
{
try
{
if (s == "MRUList")
{
continue;
}
else
{
try
{
Byte[] byteValue = (Byte[])rk.GetValue(s);
string str = BitConverter.ToString(byteValue).Replace("00", "");
str = BitConverter.ToString(byteValue).Replace("-", "");
//str binry AND VAR CONVERTED TEXT
Console.WriteLine(s + " Contains the value of : " + str);
StringBuilder sb = new StringBuilder();
for (int i = 0; i <= str.Length - 2; i += 2)
{
sb.Append(Convert.ToString(Convert.ToChar(Int32.Parse(str.Substring(i, 2), System.Globalization.NumberStyles.HexNumber))));
}
String val = Convert.ToString(sb).Replace(" ", "");
Console.WriteLine(s + " Contains the value of : " + val);
}
catch (Exception Errors)
{
Console.WriteLine("An error has occurred: " + Errors.Message);
}
}
//rk.Close();
}
catch (Exception MyError)
{
Console.WriteLine("An error has occurred: " + MyError.Message);
}
Console.WriteLine("-----------------------------------------------");
//rk.Close();
}
The binary there is unicode encoded. I fixed your code and verified it is working on my XP. However, it doesn't work on Windows 7 or Vista because LastVisitedMRU no longer exists.
static void Main(string[] args)
{
try
{
RegistryKey rk = Registry.CurrentUser;
rk = rk.OpenSubKey(#"Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32\LastVisitedMRU", false);
PrintKeys(rk);
}
catch (Exception ex)
{
Console.WriteLine("An error has occurred: " + ex.Message);
}
}
static void PrintKeys(RegistryKey rk)
{
if (rk == null)
{
Console.WriteLine("No specified registry key!");
return;
}
foreach (String s in rk.GetValueNames())
{
if (s == "MRUList")
{
continue;
}
Byte[] byteValue = (Byte[])rk.GetValue(s);
UnicodeEncoding unicode = new UnicodeEncoding();
string val = unicode.GetString(byteValue);
Console.Out.WriteLine(val);
}
Console.ReadLine();
}