I need to create guids from their string equivalents from a text dump that I get from the Mailchimp 1.0 export api.
The guids are all strings that contain the backslash \ character, for example here is (truncated) one of them:
"\"9ffd2c3-6er456ds\""
When I pass the guid to the following methods, nothing works when I then attempt Guid.TryParse.
string[] values = sub.Split(',');
string rawguid = values[3];
var guid = rawguid.Replace("\\", "");
var tguid = rawguid.Trim();
var sguid = rawguid.Normalize().ToString();
How can I properly parse these guid strings into guids?
There are no backslashes in your guid - those are escaped doublequotes inside the string : the backslash is escaping the " inside it. Use .Replace("\"","") to remove them.
Beside that - you do not have a valid GUID - there are r and a s inside - guids consist of 32 digits using only 0-9a-fA-F.
Example using Guid.ParseExact:
using System;
public class Program
{
public static void Main()
{
var guid = Guid.ParseExact(
"\"ab9ffd2c3-6e456daaaaaaaaaaaaaaaaa\"" // guid with masked " inside
.Replace("-","") // remove all - for N
.Replace("\"",""), "N"); // remove all \" as well
Console.WriteLine( guid );
}
}
to get a parsed guid:
ab9ffd2c-36e4-56da-aaaa-aaaaaaaaaaaa
Related
In my Asp.net (C#) application, I need to read three parameters from the query string (Item, Code and Location). Url is given below.
http://localhost/Reports?ITEM=A#1234&CODE=0013&LOCATION=LOCA#001
I am reading it like this.
_code = Request["CODE"]; //value should be 0013
_item = Request["ITEM"]; //value should be A#1234
_location = Request["LOCATION"]; //value should be LOCA#001
But after # character, nothing retrievable to the variables.
Our database contains lots of data items with hash(#) character. Any idea how to read with # ?
Use URL encoding for the param values urlencode
To encode or decode values outside of a web application, use the WebUtility class.
using System;
using System.Net;
public class Program
{
public static void Main()
{
string urlValue = "ITEM="+WebUtility.UrlEncode("A#1234") + "&CODE=0013&LOCATION=" + WebUtility.UrlEncode("LOCA#001");
Console.WriteLine(urlValue);
Console.WriteLine(WebUtility.UrlDecode(urlValue));
}
}
I have a program with a lot of string constants being used to allow specific characters via regular expressions. I now have a list of characters I want to block everywhere, but I don't want to have to go back through all my old string constants and rewrite them. Instead, I want to create a list of restricted characters and edit that list in only one place (in case it changes in the future). I'll then run all the string constants through a custom regular expression.
I have the list of restricted characters defined in web.config like so:
<add key="RestrChar" value="\!#%<>|&;"/>
Calling a custom regular expression like this:
[RestrictCharRegExpress(ConstantStringName, ErrorMessage = CustomErrMsg)]
public string StringName
Class is defined as follows:
public class RestrictCharRegExpressAttribute : RegularExpressionAttribute
{
public RestrictCharRegExpressAttribute(string propRegex) : base(GetRegex(propRegex)){ }
private static string GetRegex(string propRegex)
{
string restrictedChars = ConfigurationManager.AppSettings.Get("RestrChar");
return Regex.Replace(propRegex, $"[{restrictedChars}]+", "");
}
}
Now this works when ConstantStringName specifically includes some of the characters I want to exclude like this:
public const string ConstantStringName = "^[-a-z A-Z.0-9/!&\"()]{1,40}$";
! and & are explicitly included so they will get replaced with nothing. But this won't work if the characters I'm trying to exclude aren't explicitly listed and are instead included via a list like this:
public const string ConstantStringName = "^[ -~\x0A\x0D]{1,40}$";
I've tried adding a negative lookahead like this:
return propRegex + "(?![" + restrictedChars + "])";
But that doesn't work in both cases. Also tried the negated set:
int i = propRegex.IndexOf(']');
if (i != -1)
{
propRegex = propRegex.Insert(i, "[^" + restrictedChars + "]");
return propRegex;
}
Still not working for both cases. Finally I tried character class subtraction:
int i = propRegex.IndexOf(']');
if (i != -1)
{
propRegex = propRegex.Insert(i, "-[" + restrictedChars + "]");
return propRegex;
}
And once again I achieved failure.
Does anyone have any other ideas how I can achieve my goal to exclude a set of characters no matter what set of regex rules are passed into my custom regular expression?
Actually figured out what I'm trying to do:
int indexPropRegex = propRegex.IndexOf('^');
string restrictedCharsAction = "(?!.*[" + restricedChars + "]);
propRegex = indexPropRegex == -1 ? propRegex.Insert(0, restrictedCharsAction) : propRegex.Insert(indexPropRegex +1, restrictedCharsAction);
return propRegex;
I'm working on a project that uses a plain ASCII .txt file as a key/value configuration file. The current format for ConfigFile.txt is something like
FirstName=Elmer|LastName=Fudd|UserId=EFudd|Password=fubar|Date=7/29/2016
This is easy to read into the program and create a dictionary with KeyValuePairs with code something like:
using (FileStream fs = new FileStream("ConfigFile.txt", FileMode.Open))
{
using (StreamReader sr = new StreamReader(fs))
{
string fileText = sr.ReadToEnd();
// Tokenize the entire file string into separate key=value strings.
string[] tokens = fileText.Split('|');
// Iterate through all of the key=value strings, tokenize each one into a key=Value
// pair and add the key and value as separate strings into the dictionary.
foreach (string token in tokens)
{
string[] keyValuePair = token.Split('=');
configDict.Add(keyValuePair[0], keyValuePair[1]);
}
}
}
It first splits out each key/value as a separate string using the '|' as the delimiter.
FirstName=Elmer
LastName=Fudd
UserId=EFudd
Password=foobar
Date=7/29/2016
Then, for each key/value string, it separates the key and value on the '=' delimiter, creates a KeyValuePair, and inserts it into a dictionary for later lookups in the program.
So far so good. Users are instructed not to create passwords with either delimiter. However, I now have to encrypt the password before including it in the file and the encryption routine can produce any printable character from 0x20 through 0x7F. So, an encrypted password can end up with either or both of the delimiters. I can end up with 'foobar' (or whatever) being encrypted by the encryption engine into P#|=g%. This messes up the ability of the split function to work properly.
So, I want to change the delimiters typed into the Notepad .txt file to control characters so that, instead of the '|' delimiter, I am using 0x1E (Record Separator) and replace the '=' sign with 0x1F (Unit Separator).
I can escape and code this directly in C# with no problems, but how would I modify the original .txt disk file so that it will read in the delimiters as single (non-printable) characters correctly?
So, Instead of having plain text like that, What I would do is use a proper serialization format, such as JSON.
There are tools out there that do the hard work for you.
The built-in System.Web.Script.Serialization namespace has some tools that you can use, but I prefer to use Json.Net. If you have Visual Studio, you can install it with nuGet(let me know in the comments if you need more help than that).
But once you add it to your project, you can do something like this
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
namespace ConsoleApplication1
{
public class Program
{
static void Main(string[] args)
{
var dict = new Dictionary<string, string>();
dict.Add("FirstName", "Elmer");
dict.Add("LastName", "Fudd");
dict.Add("Password", #"\a\ansld\sb\b8d95nj");
var json = JsonConvert.SerializeObject(dict);
File.WriteAllText("ConfigFile.txt, json);
var txt = File.ReadAllText("ConfigFile.txt");
var newDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(txt);
}
}
}
and ConfigFile.txt will look like this
{"FirstName":"Elmer","LastName":"Fudd","Password":"\\a\\ansld\\sb\\b8d95nj"}
If you want it more human-readable, use
var json = JsonConvert.SerializeObject(dict, Formatting.Indented);
and you'll get
{
"FirstName": "Elmer",
"LastName": "Fudd",
"Password": "\\a\\ansld\\sb\\b8d95nj"
}
You can convert integers to chars so just do this...
string[] tokens = fileText.Split((char)0x1e);
// ...
string[] keyValuePair = token.Split((char)0x1f);
... but encoding your passwords as base64 would be easier and cleaner...
string base64 = Convert.ToBase64String(passwordHash);
byte[] passwordHash = Convert.FromBase64String(base64);
... NOTE:
it is possible that the hashes/encrypted data will contain these characters so I wouldn't just dump the hases into the text file.
The following class extract the string segments using Regular Expressions and support password with non-printable characters : 0x00 .. 0xFF
The class include properties to the segments of the configuration
you can run Demo Example at .NEt Fiddle
using System;
using System.Text.RegularExpressions;
class ConfigParser
{
public string Text { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserId { get; set; }
public string Password { get; set; }
public string Date { get; set; }
public ConfigParser(string text)
{
Text =text;
Parse(text);
}
private static string pattern = #"
^FirstName=(?<firstname>\w+) \|
LastName=(?<lastname>\w+) \|
UserId=(?<userid>\w+) \|
Password=(?<pasword>.+)
Date=(?<date>.+)
$
";
private Regex regex = new Regex(pattern,
RegexOptions.Singleline
| RegexOptions.ExplicitCapture
| RegexOptions.CultureInvariant
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
private void Parse(string text)
{
Console.WriteLine("text: {0}",text);
Match m = regex.Match(text);
FirstName = m.Groups["firstname"].ToString();
LastName = m.Groups["lastname"].ToString();
UserId = m.Groups["userid"].ToString();
Password = m.Groups["pasword"].ToString();
Date = m.Groups["date"].ToString();
}
}
How to use:
var text ="your text here";
var c = new ConfigParser(text );
you can access the properties of the class: FirstName, LastName,....
Console.WriteLine("firstname: {0}", c.FirstName);
Console.WriteLine("lastname: {0}", c.LastName);
Console.WriteLine("UserId: {0}", c.UserId);
Console.WriteLine("Password: {0}", c.Password);
Console.WriteLine("date {0}", c.Date);
Sample output:
The password include non-printable characters | separator and symbols
text: FirstName=Elmer|LastName=Fudd|UserId=EFudd|Password=fg%|uy|◄¶|hj↑khg|Date=7/29/2016
firstname: Elmer
lastname: Fudd
UserId: EFudd
Password: fg%|uy|◄¶|hj↑khg
date: 7/29/2016
Easiest Answer:
Insert the special characters into the string using the ALT-numberpad value trick. Record Group ALT-31 (▼) to delimit the end of a Key/Value pair and Item Group ALT-30 (▲) to delimit the key from the value. Save the string as UTF-8.
Code for delimiters is
private static char tokenDelimiter = ('▲');
private static char keyValuePairDelimiter = ('▼');
using the same ALT-numberpad trick to put in the up and down triangles. Include instructions that the black triangles are NEVER to be edited or removed and explain their meaning.
It takes me back to my old DOS days. Simple, and took 5 minutes to implement - and it doesn't require that the existing code base be materially changed - just the two delimiter characters changed.
I am reading the contents of an XLS file. Some older versions of excel add what I assume are escape sequences within the cell that causes me problems upon attempting to create a SQL column of that name.
Example string I have to work with is passed as
\0\0K\0\b\0Job
I would like to return this string as "Job". None of the replace sequences in the following job make a change and it returns as
\0\0K\0\b\0Job
C# does not allow that string to be created manually without escaping it with "\\", which defeats the purpose of what I need.
Any suggestions?
public static string CleanupHeaders(string _Col)
{
// Replace your #"\" parameter with double-escaped: #"\\"
_Col = _Col.Replace(#"\\0K", "");
_Col = _Col.Replace(#"\\b", "");
_Col = _Col.Replace(#"\\0", "");
return _Col;
}
Any suggestions?
I have one, since the string comes in as "\0\0K\0\b\0Job" your string replace methods _Col.Replace shouldn't need to use the literal syntax. In C# the \ is an escape character and the following characters create an escape sequence.
The issue is the verbatim string with the # syntax. Remove that and you get "Job". See this working .NET Fiddle - it has several demonstrations that will easily show you what happens. Take a look # MSDN's reference on string literals for more details.
public static string CleanupHeaders(string _Col)
{
_Col = _Col.Replace("\0K", "");
_Col = _Col.Replace("\b", "");
_Col = _Col.Replace("\0", "");
return _Col;
}
There should be no reason to use them in this situation.
Updated
The OP altered the question a little, so here's an update .NET Fiddle.
It's possible that the thing that's reporting the content of the string to you is reporting actual zero characters as \0 for human readability.
Try removing the #s from your replacement strings there.
The code that you provided should be working exactly as expected as seen in this example.
It's All In How It's Called
Since you mentioned that your initial string isn't being changed, it's worth noting that your replace function actually returns a string and doesn't perform an inline replacement, so you'll need to call it through :
// This will set your original string to the result of your CleanupHeaders() method
yourColumnVariable = CleanupHeaders(yourColumnVariable);
If you do want to perform an inline replacement of your existing string, simply update your CleanupHeaders() method to use a ref parameter to perform an update to the actual reference that was passed in :
// Notice the ref keyword
public static void CleanupHeaders(ref string _Col)
{
_Col = _Col.Replace(#"\0K", "");
_Col = _Col.Replace(#"\b", "");
_Col = _Col.Replace(#"\0", "");
}
and then you could simply call it using :
// This will update the yourColumnVariable to reflect any changes made in the method
CleanupHeaders(ref yourColumnVariable);
You can see an updated example that uses the ref approach here.
If you have a debugger, I would first of all suggest seeing what value the _Col string is when it's passed into your CleanupHeaders() method.
Depending where the string:
"\0\0K\0\b\0Job"
came from; I would imagine it is already escaped when it reaches your code.
The string would look something like this: "\\0\\0K\\0\\b\\0Job" when it reaches your method.
I would suggest 1 of 2 things:
1: Replace all your \ in the string with - or any character of your choice:
_Col = _Col.Replace(#"\\", "-");
And then replace your matching strings that now have the - prefix:
// Replace all your escaped backslashes
_Col = _Col.Replace(#"\\", "-");
// Now replace your new prefix + values you are looking to replace
_Col = _Col.Replace("-0K", "");
_Col = _Col.Replace("-0", "");
_Col = _Col.Replace("-b", "");
return _Col;
Or
2: \0 Is recognised as a character as it's escaped; so it's not being printed/output. Try changing your .Replace(#"\0", ""); with .Replace(#"\\0", ""); like so:
public static string CleanupHeaders(string _Col)
{
_Col = _Col.Replace(#"\\0K", ""); // Replaces the exact already escaped \\ value.
_Col = _Col.Replace(#"\\b", "");
_Col = _Col.Replace(#"\\0", "");
return _Col;
}
Is there an easy way in C# to read a properties file that has each property on a separate line followed by an equals sign and the value, such as the following:
ServerName=prod-srv1
Port=8888
CustomProperty=Any value
In Java, the Properties class handles this parsing easily:
Properties myProperties=new Properties();
FileInputStream fis = new FileInputStream (new File("CustomProps.properties"));
myProperties.load(fis);
System.out.println(myProperties.getProperty("ServerName"));
System.out.println(myProperties.getProperty("CustomProperty"));
I can easily load the file in C# and parse each line, but is there a built in way to easily get a property without having to parse out the key name and equals sign myself? The C# information I have found seems to always favor XML, but this is an existing file that I don't control and I would prefer to keep it in the existing format as it will require more time to get another team to change it to XML than parsing the existing file.
No there is no built-in support for this.
You have to make your own "INIFileReader".
Maybe something like this?
var data = new Dictionary<string, string>();
foreach (var row in File.ReadAllLines(PATH_TO_FILE))
data.Add(row.Split('=')[0], string.Join("=",row.Split('=').Skip(1).ToArray()));
Console.WriteLine(data["ServerName"]);
Edit: Updated to reflect Paul's comment.
Final class. Thanks #eXXL.
public class Properties
{
private Dictionary<String, String> list;
private String filename;
public Properties(String file)
{
reload(file);
}
public String get(String field, String defValue)
{
return (get(field) == null) ? (defValue) : (get(field));
}
public String get(String field)
{
return (list.ContainsKey(field))?(list[field]):(null);
}
public void set(String field, Object value)
{
if (!list.ContainsKey(field))
list.Add(field, value.ToString());
else
list[field] = value.ToString();
}
public void Save()
{
Save(this.filename);
}
public void Save(String filename)
{
this.filename = filename;
if (!System.IO.File.Exists(filename))
System.IO.File.Create(filename);
System.IO.StreamWriter file = new System.IO.StreamWriter(filename);
foreach(String prop in list.Keys.ToArray())
if (!String.IsNullOrWhiteSpace(list[prop]))
file.WriteLine(prop + "=" + list[prop]);
file.Close();
}
public void reload()
{
reload(this.filename);
}
public void reload(String filename)
{
this.filename = filename;
list = new Dictionary<String, String>();
if (System.IO.File.Exists(filename))
loadFromFile(filename);
else
System.IO.File.Create(filename);
}
private void loadFromFile(String file)
{
foreach (String line in System.IO.File.ReadAllLines(file))
{
if ((!String.IsNullOrEmpty(line)) &&
(!line.StartsWith(";")) &&
(!line.StartsWith("#")) &&
(!line.StartsWith("'")) &&
(line.Contains('=')))
{
int index = line.IndexOf('=');
String key = line.Substring(0, index).Trim();
String value = line.Substring(index + 1).Trim();
if ((value.StartsWith("\"") && value.EndsWith("\"")) ||
(value.StartsWith("'") && value.EndsWith("'")))
{
value = value.Substring(1, value.Length - 2);
}
try
{
//ignore dublicates
list.Add(key, value);
}
catch { }
}
}
}
}
Sample use:
//load
Properties config = new Properties(fileConfig);
//get value whith default value
com_port.Text = config.get("com_port", "1");
//set value
config.set("com_port", com_port.Text);
//save
config.Save()
Most Java ".properties" files can be split by assuming the "=" is the separator - but the format is significantly more complicated than that and allows for embedding spaces, equals, newlines and any Unicode characters in either the property name or value.
I needed to load some Java properties for a C# application so I have implemented JavaProperties.cs to correctly read and write ".properties" formatted files using the same approach as the Java version - you can find it at http://www.kajabity.com/index.php/2009/06/loading-java-properties-files-in-csharp/.
There, you will find a zip file containing the C# source for the class and some sample properties files I tested it with.
Enjoy!
Yet another answer (in January 2018) to the old question (in January 2009).
The specification of Java properties file is described in the JavaDoc of java.util.Properties.load(java.io.Reader). One problem is that the specification is a bit complicated than the first impression we may have. Another problem is that some answers here arbitrarily added extra specifications - for example, ; and ' are regarded as starters of comment lines but they should not be. Double/single quotations around property values are removed but they should not be.
The following are points to be considered.
There are two kinds of line, natural lines and logical lines.
A natural line is terminated by \n, \r, \r\n or the end of the stream.
A logical line may be spread out across several adjacent natural lines by escaping the line terminator sequence with a backslash character \.
Any white space at the start of the second and following natural lines in a logical line are discarded.
White spaces are space (, \u0020), tab (\t, \u0009) and form feed (\f, \u000C).
As stated explicitly in the specification, "it is not sufficient to only examine the character preceding a line terminator sequence to decide if the line terminator is escaped; there must be an odd number of contiguous backslashes for the line terminator to be escaped. Since the input is processed from left to right, a non-zero even number of 2n contiguous backslashes before a line terminator (or elsewhere) encodes n backslashes after escape processing."
= is used as the separator between a key and a value.
: is used as the separator between a key and a value, too.
The separator between a key and a value can be omitted.
A comment line has # or ! as its first non-white space characters, meaning leading white spaces before # or ! are allowed.
A comment line cannot be extended to next natural lines even its line terminator is preceded by \.
As stated explicitly in the specification, =, : and white spaces can be embedded in a key if they are escaped by backslashes.
Even line terminator characters can be included using \r and \n escape sequences.
If a value is omitted, an empty string is used as a value.
\uxxxx is used to represent a Unicode character.
A backslash character before a non-valid escape character is not treated as an error; it is silently dropped.
So, for example, if test.properties has the following content:
# A comment line that starts with '#'.
# This is a comment line having leading white spaces.
! A comment line that starts with '!'.
key1=value1
key2 : value2
key3 value3
key\
4=value\
4
\u006B\u0065\u00795=\u0076\u0061\u006c\u0075\u00655
\k\e\y\6=\v\a\lu\e\6
\:\ \= = \\colon\\space\\equal
it should be interpreted as the following key-value pairs.
+------+--------------------+
| KEY | VALUE |
+------+--------------------+
| key1 | value1 |
| key2 | value2 |
| key3 | value3 |
| key4 | value4 |
| key5 | value5 |
| key6 | value6 |
| : = | \colon\space\equal |
+------+--------------------+
PropertiesLoader class in Authlete.Authlete NuGet package can interpret the format of the specification. The example code below:
using System;
using System.IO;
using System.Collections.Generic;
using Authlete.Util;
namespace MyApp
{
class Program
{
public static void Main(string[] args)
{
string file = "test.properties";
IDictionary<string, string> properties;
using (TextReader reader = new StreamReader(file))
{
properties = PropertiesLoader.Load(reader);
}
foreach (var entry in properties)
{
Console.WriteLine($"{entry.Key} = {entry.Value}");
}
}
}
}
will generate this output:
key1 = value1
key2 = value2
key3 = value3
key4 = value4
key5 = value5
key6 = value6
: = = \colon\space\equal
An equivalent example in Java is as follows:
import java.util.*;
import java.io.*;
public class Program
{
public static void main(String[] args) throws IOException
{
String file = "test.properties";
Properties properties = new Properties();
try (Reader reader = new FileReader(file))
{
properties.load(reader);
}
for (Map.Entry<Object, Object> entry : properties.entrySet())
{
System.out.format("%s = %s\n", entry.getKey(), entry.getValue());
}
}
}
The source code, PropertiesLoader.cs, can be found in authlete-csharp. xUnit tests for PropertiesLoader are written in PropertiesLoaderTest.cs.
I've written a method that allows emty lines, outcommenting and quoting within the file.
Examples:
var1="value1"
var2='value2'
'var3=outcommented
;var4=outcommented, too
Here's the method:
public static IDictionary ReadDictionaryFile(string fileName)
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
foreach (string line in File.ReadAllLines(fileName))
{
if ((!string.IsNullOrEmpty(line)) &&
(!line.StartsWith(";")) &&
(!line.StartsWith("#")) &&
(!line.StartsWith("'")) &&
(line.Contains('=')))
{
int index = line.IndexOf('=');
string key = line.Substring(0, index).Trim();
string value = line.Substring(index + 1).Trim();
if ((value.StartsWith("\"") && value.EndsWith("\"")) ||
(value.StartsWith("'") && value.EndsWith("'")))
{
value = value.Substring(1, value.Length - 2);
}
dictionary.Add(key, value);
}
}
return dictionary;
}
Yeah there's no built in classes to do this that I'm aware of.
But that shouldn't really be an issue should it? It looks easy enough to parse just by storing the result of Stream.ReadToEnd() in a string, splitting based on new lines and then splitting each record on the = character. What you'd be left with is a bunch of key value pairs which you can easily toss into a dictionary.
Here's an example that might work for you:
public static Dictionary<string, string> GetProperties(string path)
{
string fileData = "";
using (StreamReader sr = new StreamReader(path))
{
fileData = sr.ReadToEnd().Replace("\r", "");
}
Dictionary<string, string> Properties = new Dictionary<string, string>();
string[] kvp;
string[] records = fileData.Split("\n".ToCharArray());
foreach (string record in records)
{
kvp = record.Split("=".ToCharArray());
Properties.Add(kvp[0], kvp[1]);
}
return Properties;
}
Here's an example of how to use it:
Dictionary<string,string> Properties = GetProperties("data.txt");
Console.WriteLine("Hello: " + Properties["Hello"]);
Console.ReadKey();
The real answer is no (at least not by itself). You can still write your own code to do it.
C# generally uses xml-based config files rather than the *.ini-style file like you said, so there's nothing built-in to handle this. However, google returns a number of promising results.
I don't know of any built-in way to do this. However, it would seem easy enough to do, since the only delimiters you have to worry about are the newline character and the equals sign.
It would be very easy to write a routine that will return a NameValueCollection, or an IDictionary given the contents of the file.
You can also use C# automatic property syntax with default values and a restrictive set. The advantage here is that you can then have any kind of data type in your properties "file" (now actually a class). The other advantage is that you can use C# property syntax to invoke the properties. However, you just need a couple of lines for each property (one in the property declaration and one in the constructor) to make this work.
using System;
namespace ReportTester {
class TestProperties
{
internal String ReportServerUrl { get; private set; }
internal TestProperties()
{
ReportServerUrl = "http://myhost/ReportServer/ReportExecution2005.asmx?wsdl";
}
}
}
There are several NuGet packages for this, but all are currently in pre-release version.
Capgemini.Cauldron.Core.JavaProperties 2.0.39-beta
Kajabity.Tools.Java 0.2.6638.28124
[Update]
As of June 2018, Capgemini.Cauldron.Core.JavaProperties is now in a stable version (version 2.1.0 and 3.0.20).
I realize that this isn't exactly what you're asking, but just in case:
When you want to load an actual Java properties file, you'll need to accomodate its encoding. The Java docs indicate that the encoding is ISO 8859-1, which contains some escape sequences that you might not correctly interpret. For instance look at this SO answer to see what's necessary to turn UTF-8 into ISO 8859-1 (and vice versa)
When we needed to do this, we found an open-source PropertyFile.cs and made a few changes to support the escape sequences. This class is a good one for read/write scenarios. You'll need the supporting PropertyFileIterator.cs class as well.
Even if you're not loading true Java properties, make sure that your prop file can express all the characters you need to save (UTF-8 at least)
No there is not : But I have created one easy class to help :
public class PropertiesUtility
{
private static Hashtable ht = new Hashtable();
public void loadProperties(string path)
{
string[] lines = System.IO.File.ReadAllLines(path);
bool readFlag = false;
foreach (string line in lines)
{
string text = Regex.Replace(line, #"\s+", "");
readFlag = checkSyntax(text);
if (readFlag)
{
string[] splitText = text.Split('=');
ht.Add(splitText[0].ToLower(), splitText[1]);
}
}
}
private bool checkSyntax(string line)
{
if (String.IsNullOrEmpty(line) || line[0].Equals('['))
{
return false;
}
if (line.Contains("=") && !String.IsNullOrEmpty(line.Split('=')[0]) && !String.IsNullOrEmpty(line.Split('=')[1]))
{
return true;
}
else
{
throw new Exception("Can not Parse Properties file please verify the syntax");
}
}
public string getProperty(string key)
{
if (ht.Contains(key))
{
return ht[key].ToString();
}
else
{
throw new Exception("Property:" + key + "Does not exist");
}
}
}
Hope this helps.