I have a List<string> that I would like to populate via a text file that is set as a project resource. I have looked all over on a way to do this but haven't yet found one that doesn't cause my program to crash.
If I manually populate the list...
_names.Add("Sam");
_names.Add("John");
_names.Add("Mike");
...everything works. My text file has each name on a separate line, no commas or anything. When I try to read in the names, the program crashes, no matter which route I take. This is the most recent way I've tried, though there are many others:
using (var reader = new StreamReader(Properties.Resources.sampleNamesMale))
{
string line;
while ((line = reader.ReadLine()) != null)
{
_names.Add(line);
}
}
Also, I can't isolate the reason for the crash because every time it does, the error just mentions ViewModelLocator, which is entirely irrelevant to this issue.
Does anybody have any ideas about how to fix this? I would certainly appreciate any advice.
Update: Try-catch yields no results. This is the error I get:
XamlParseException occurred - 'The invocation of the constructor on type 'AoW.ViewModels.ViewModelLocator' that matches the specified binding constraints threw an exception.' Line number '13' and line position '10'.
It points at InitializeComponent() in my main window's constructor.
Update 2: The real exception is this:
"ArgumentException occurred - Illegal characters in path." It points at the using (var reader.... line.
Use a StringReader instead of a StreamReader:
using (var reader = new StringReader(Properties.Resources.sampleNamesMale))
You are getting that error because StreamReader(string) expects a file path. If you are providing the actual text in Properties.Resources.sampleNamesMale, you have to use a StringReader.
The only way you could get the exception:
ArgumentException occurred - Illegal characters in path.
is if the path returned by Properties.Resources.sampleNamesMale was literally invalid:
using (var reader = new StreamReader(Properties.Resources.sampleNamesMale))
After second update the answer is very easy: display in debugger what is a path to your file and make it correct. Probably it contains spaces in the end or not escaped \
Related
I am completely stumped on this one, I have a static class attempting to detect if a directory exists, but for some reason, it throws the following error:
Program.Main encountered an error: Object reference not set to an instance of an object. Stack trace: at csv.prepareCSVData() in path/csv.cs:line 21
at RLCSVTools.Program.Main(String[] args) in path\Program.cs:line 31
This is the code that produces that error in csv.cs.prepareCSVData:
ConfigurationSync.logDebugMessage(logMessageType.warning, "CSV class Dir: " + exportPath);
//this log works and reveals exportPath has been populated
if (Directory.Exists(exportPath) == false)
//breaks here regardless of dir existing or not
{
ConfigurationSync.logDebugMessage(logMessageType.warning, "Recreating the directory: " + exportPath);
// I have never seen this log run
Directory.CreateDirectory(exportPath);
}
I have added some comments in the code to show at exactly what line the error occurs.
All members of this class, including the class, are static. public static class csv
Has anyone experienced anything like this? I can't seem to find a solution.
So lets look at the documentation
Directory.Exists(String) Method
Doesn't throw any exception
CreateDirectory(String)
Creates all directories and subdirectories in the specified path
unless they already exist.
Exceptions
IOException
The directory specified by path is a file.
-or-
The network name is not known.
UnauthorizedAccessException
The caller does not have the required permission.
ArgumentException
path is a zero-length string, contains only white space, or contains one or more invalid characters. You can query for invalid
characters by using the GetInvalidPathChars() method.
-or-
path is prefixed with, or contains, only a colon character (:).
ArgumentNullException
path is null.
PathTooLongException
The specified path, file name, or both exceed the system-defined maximum length.
DirectoryNotFoundException
The specified path is invalid (for example, it is on an unmapped drive).
NotSupportedException
path contains a colon character (:) that is not part of a drive label ("C:\").
Its clear that CreateDirectory(String) is not your problem
So by deducation the only obvious issue here is exportPath is null
For which this is relevant
What is a NullReferenceException, and how do I fix it?
if exportPath is not null, then you need to debug your application, something is not what it seems
I have the following c# code in a WPF app:
var command = new OleDbCommand($"CREATE INDEX idx{index.ColumnName} ON {tableConfig.Name}({index.ColumnName})", _targetCon);
try
{
command.ExecuteNonQuery();
}
catch (Exception ex1) { _serilog.WriteError(METHOD_NAME, "Trouble adding index onto Access column", ex1); }
My problem is that when stepping through the code in the VS debugger, the line "command.ExecuteNonQuery();" is throwing an exception. At the time of the exception, the value of _targetCon.ConnectionString is "Provider=Microsoft.Jet.OleDb.4.0;Data Source=C:\AccessDatabases\APMS\unit3.mdb;" and the value of the _targetCon.DataSource is: C:\AccessDatabases\APMS\unit3.mdb This is the correct path. However, the value of ex2.Message is "Could not find file 'C:\Git_RB\AccessMigration\AccessLauncher\AccessLauncher.WPF\bin\Debug\Unit3.mdb'"
If I run the app outside of VS then I find that it's still trying to find the file in the database in the same folder as the exe:
Why is the command object ignoring the properties of its connection object and looking in the wrong path?
Check the actual value of the SQL statement that you are using. It might contain another table name than the one you expect, e.g. due to string truncation.
When I'm parsing a text file, and importing it in my application through the (truly wonderful) FileHelpers library, for each error that occurs I want to log in a separate text file the record that failed (along with the error of course), like
Error: The record ..... failed with error ....
This brings the question in the title: I see there's the method
WriteString(IEnumerable<T>), but if I call
string recordAsString = engine.WriteString(new List<T>() { record });
the result string contains a new line in it, and the only way I managed to "clean" it is
recordAsString = recordAsString.Substring(0, recordAsString.Length - 2);
Is there a cleaner way, ie a method that returns the record as a string that doesn't contain any new line?
Thank you
You can try with
var recordAsString = engine.Options.RecordToString(record);
Thanks for using the library
I am trying to use the PDBSTR.EXE tool to merge version information into a PDB file and from time to time I encounter the following error:
[result: error 0x3 opening K:\dev\main\bin\mypdbfile.pdb] <- can be a different PDB file.
An example of the command line that I use is:
pdbstr.exe -w -s:srcsrv -p:K:\dev\main\bin\mypdbfile.pdb -i:C:\Users\username\AppData\Local\Temp\tmp517B.stream
Could you tell me what would cause error code 0x3?
If the error code is similar to the standard System error code 3 ERROR_PATH_NOT_FOUND, then it seems to think that the path K:\dev\main\bin\mypdbfile.pdb does NOT exist when in fact it DOES.
However please note that my K: drive is a SUBST'ed drive.
(System error code reference https://msdn.microsoft.com/en-ca/library/windows/desktop/ms681382(v=vs.85).aspx)
Do you know what the 0x3 error code could possibly mean?
If this error code appears from time to time, then i guess the ERROR_PATH_NOT_FOUND might be the real problem.
I guess the cause is, i couldn't see any double quotes wrapping the path you've given as input. When the path contains a folder name with spaces in it, it breaks your path. For ex
pdbstr.exe -w -s:srcsrv -p:K:\dev\main\my folder with spaces\mypdbfile.pdb -i:C:\Users\username\AppData\Local\Temp\tmp517B.stream
Add a double quote around the path and that might solve it. Hope it helps.
This question might be quite localised, but I really need another opinion on what I'm doing wrong here. How can I be passing illegal characters in a path to a temporary file when at every stage of the process, everything appears to be fine and normal?
I'm getting this:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentException: Illegal characters in path.
When passing this:
"C:\Documents and Settings\<username>\Local Settings\Temp\1\tmp1E0.tmp"
to this:
XmlDocument doc = new XmlDocument();
doc.Load(<above string>);
The file exists in the location specified (I've checked it during execution) although System.IO.File.Exists thinks otherwise; I cannot see anything obvious. Is there anything I could try to work around it?
More code available upon request:
REQ1: How is your path being declared?
try
{
session.TempConfigDir = System.IO.Path.GetTempFileName();
//All work done with the temp file happens within the Form
Form currentform = new WelcomeDialog(session);
DialogResult dr = currentform.ShowDialog();
}
finally
{
File.Delete(session.TempConfigDir);
}
The session variable is passed around to various locations, but is not altered.
REQ2: Are you actually using <username>?
No, I edited it out. It's a valid windows username.
REQ3: What do you get back from debugging?
This is actually happening within an installer (which is slightly difficult to physically debug) but the above string is an example from what I can get from the logs, with the valid username, of course.
REQ4: More code on how it's used?
I'm adding the WiX tag because this involves WiX3.7.
Basic Data holding class:
public class SessionState
{
//<other properties>
public string TempConfigDir { get; set; }
public SessionState()
{
//Setting of properties
}
}
From within the Form:
//StringBuilder for arguments
installerargs.Append("\" TEMPCONFIGDIR=\"");
installerargs.Append(m_Session.TempConfigDir);
//...
Process p = Process.Start("msiexec", installerargs.ToString());
p.WaitForExit();
APPEND: Part missed from Form:
//It's grabbing the web.config from an existing install
//and copying it over the temp file, not changing its location or name.
File.Copy(m_Session.INSTALLDIR + DIR_WEB_CONFIG, m_Session.TempConfigDir, true);
From within WiX3.7's MSI:
<Property Id="TEMPCONFIGDIR" Value="UNSET" />
...
<Custom Action="CA_InstallUICA.SetProp" After="StartServices">NOT Installed</Custom>
<Custom Action="CA_InstallUICA" After="CA_InstallUICA.SetProp">NOT Installed</Custom>
...
<CustomAction Id="CA_InstallUICA.SetProp" Property="CA_InstallUICA" Value="rcswebdir=[MCWSVDIR];webdir=[WEBAPPVDIR];installtype=notransaction;targetdir=[INSTALLDIR];interaction=[INTERACTION];tempconfigdir="[TEMPCONFIGDIR]";" />
From Within the Custom Action that uses it:
wz.AutoSettings.TempConfigLocation = session.CustomActionData["tempconfigdir"];
//Where I get the above string passed out
session.Log(wz.AutoSettings.TempConfigLocation);
//The rest of the code that uses it is above and where the exception is thrown
REQ5: Do you change the TempConfigDir variable to something.xml?
No, I copy an xml file over the exact name/directory that's supplied (including .tmp).
REQ6: Are you sure it's happening on .Load()?
Yes, I've logged each side of the line and only hit the first one when executing.
This line seems suspect:
<CustomAction Id="CA_InstallUICA.SetProp" Property="CA_InstallUICA" Value="rcswebdir=[MCWSVDIR];webdir=[WEBAPPVDIR];installtype=notransaction;targetdir=[INSTALLDIR];interaction=[INTERACTION];tempconfigdir="[TEMPCONFIGDIR]";" />
The portion quoting the path appears likely to be doubling the quotes, thus producing the exception:
tempconfigdir="[TEMPCONFIGDIR]"
Remove the "e; wrapping to deliver the actual path:
tempconfigdir=[TEMPCONFIGDIR]