Get all strings from resourcemanager - c#

I need to write a program, that reads all string resources from dll and insert them into some table. I have the method, that reads resources:
private static IEnumerable<KeyValuePair<string,string>> getAllResources(ResourceManager resourceManager,
Language language)
{
ResourceSet resourceSet = resourceManager.GetResourceSet(getCulture(language), true, true);
IDictionaryEnumerator dictNumerator = resourceSet.GetEnumerator();
// Get all string resources
while (dictNumerator.MoveNext())
{
// Only string resources
if (dictNumerator.Value is string)
{
var key = (string)dictNumerator.Key;
var value = (string)dictNumerator.Value;
yield return new KeyValuePair<string, string>(key, value);
}
}
}
But when I started using it, I noticed that it also reads the resources, that added like a file (reads file content)
How can I ignore resources that are added as a "file", and read only strings?

There is no way of doing that.
Have a look to the resource section of you assembly through Reflector, for instance. Your text file is saved as String. There is no difference between String value and Text File value.
Binary files, however, won't be a problem, as for binary file types you'll have byte[] as value and not string.

Related

Unity Arabic Text From JSON File

My problem is that when I get -for example- the word "سلام" from a JSON file, the output will be "????", but if I get -for example- "Peace" from the same JSON file, the output will be "Peace".
This the game that I am using (I get it from this Unity tutorial):
private void LoadGameData()
{
// Path.Combine combines strings into a file path
// Application.StreamingAssets points to Assets/StreamingAssets in the Editor, and the StreamingAssets folder in a build
string filePath = Path.Combine(Application.streamingAssetsPath, gameDataFileName);
if (File.Exists(filePath))
{
// Read the json from the file into a string
string dataAsJson = File.ReadAllText(filePath);
// Pass the json to JsonUtility, and tell it to create a GameData object from it
GameData loadedData = JsonUtility.FromJson<GameData>(dataAsJson);
// Retrieve the allRoundData property of loadedData
allRoundData = loadedData.al_asallRoundDataela;
}
else
{
Debug.LogError("Cannot load game data!");
}
}
Can anyone help me?
This is likely due to a mismatch in the Encoding. Use the ReadAllText overload which allows you to specify the proper Encoding to use when reading the file.
The default overload will assume UTF-8 unless it can detect UTF-32. Any other encoding will come through incorrectly.
I think the right code is:
var arabic = Encoding.GetEncoding(1256);
File.ReadAllText(filePath,arabic);

C# WritePrivateProfileString() value other than English language

I am trying to save a file path in ini file which contains a folder in Arabic language. i.e.
D:\ملف جديد\Checking Folder
But after using WritePrivateProfileString() to write it in settings.ini . It shows path as follows:
D:\??? ????\Checking Folder
What should I do to save the path correctly?
Edit:
Following is the code I am using to write ini file
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
You have to use System.Text.Encoding.GetEncoding("Arabic") for using Arabic Text in the path
Like for example if you want to read and write in the file than
using (var reader = new System.IO.StreamReader("YourFilePath", System.Text.Encoding.GetEncoding("Arabic")))
{
}
using (var writer = new System.IO.StreamWriter("YourFilePath", true, System.Text.Encoding.GetEncoding("Arabic")))
{
}
You could try out my INI library, I created it in order to have a friendlier (and more meaningful / intuitive) API then those WritePrivateProfile APIs.
Here is a sample of how you can use it:
// Your inputs.
string section, key, val, filePath;
var iniOptions = new IniOptions();
iniOptions.Encoding = Encoding.UTF8;
var ini = new IniFile(iniOptions);
ini.Load(filePath);
IniSection iniSection = ini.Sections[section];
IniKey iniKey = iniSection.Keys[key];
iniKey.Value = val;
ini.Save(filePath);
I hope this helps.

Create variables from text file

I want to store variables in a .txt file - like I always see in peoples config.txt files, where it's like:
var_name = ['"test url"']
I've got the code below that opens the file and reads it (at the moment just debugging and displays what's in the file, at the moment just 1 variable)
System.IO.StreamReader myFile = new System.IO.StreamReader("C:\\conf\\config.txt");
string myString = myFile.ReadToEnd();
myFile.Close();
MessageBox.Show(myString);
What's in the file is
file_name="C:\\test.txt"
Now I'd like to be able to use that variable in my functions in my VB form. How do I go about doing this? And also, how can I do multiple; so I can have basically a big list of vars that the form loads at launch?
So for example:
// Opens file and reads all variables
// Saves all variables to form
// Can now use varaible in form, e.g. messageBox.Show(file_name);
I'm new to C#, I imagine it's similar to an include but the include is local instead of part of the project.
Disclamer: standard practice (i.e. Settings) usually is the best policy, however the question has been asked and can be asnwered:
I suggest using dictionary, e.g.
Dictionary<String, String> MySettings = File
.ReadLines(#"C:\conf\config.txt")
.ToDictionary(line => line.Substring(0, line.IndexOf('=')).Trim(),
line => line.Substring(line.IndexOf('=') + 1).Trim().Trim('"'));
...
String testUrl = MySettings[var_name];
However, if you prefer "variables" you can try ExpandoObject:
dynamic ExpSettings = new ExpandoObject();
var expandoDic = (IDictionary<string, object>) ExpSettings;
foreach (var pair in MySettings)
expandoDic.Add(pair.Key, pair.Value);
...
String testUrl = ExpSettings.var_name;
I store and load data (or variables) with Json Deserialization/ serialization in c#.
Here is Serialiazation: I make an object (postlist which is an object list) that i want to save in a text file That way:
private void save_file()
{
string path = Directory.GetCurrentDirectory() + #"\list.txt";
string json = JsonConvert.SerializeObject(postlist);
File.WriteAllText(path, json);
Application.Exit();
}
You need to install Newtonsoft.Json: http://www.newtonsoft.com/json
.You can do it with the Nuget tool console.
Don"t forget to use:
using Newtonsoft.Json;
Here is a way to get all your data from the text file, this is the deserialization:
private void read_file_list()
{
string line;
try
{
using (StreamReader sr = new StreamReader("list.txt"))
{
line = sr.ReadToEnd();
}
JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings();
jsonSerializerSettings.MissingMemberHandling = MissingMemberHandling.Ignore;
postlist = JsonConvert.DeserializeObject<List<Post>>(line, jsonSerializerSettings);
}
catch
{
// catch your exception if you want
}
}
And here is how i store all my text in my object list "postlist".
Newtonsoft is very usefull and easy to use, i mostly use it to get data from api's.
This my first answer I hope it will help you.

An unhandled exception of type 'System.OutOfMemoryException' occurred in mscorlib.dll in LINQ Search

Using this article from MSDN, I'm trying to search through files in a directory. The problem is, every time I execute the program, I get:
"An unhandled exception of type 'System.OutOfMemoryException' occurred in mscorlib.dll".
I have tried to some other options like StreamReader, but I can't get it to work. These files are HUGE. Some of them range in upwards to 1.5-2GB each and there could be 5 or more files per day.
This code fails:
private static string GetFileText(string name)
{
var fileContents = string.Empty;
// If the file has been deleted since we took
// the snapshot, ignore it and return the empty string.
if (File.Exists(name))
{
fileContents = File.ReadAllText(name);
}
return fileContents;
}
Any ideas what could be happening or how to make it read without memory errors?
Entire code (in case you don't want to open the MSDN article)
class QueryContents {
public static void Main()
{
// Modify this path as necessary.
string startFolder = #"c:\program files\Microsoft Visual Studio 9.0\";
// Take a snapshot of the file system.
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(startFolder);
// This method assumes that the application has discovery permissions
// for all folders under the specified path.
IEnumerable<System.IO.FileInfo> fileList = dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories);
string searchTerm = #"Visual Studio";
// Search the contents of each file.
// A regular expression created with the RegEx class
// could be used instead of the Contains method.
// queryMatchingFiles is an IEnumerable<string>.
var queryMatchingFiles =
from file in fileList
where file.Extension == ".htm"
let fileText = GetFileText(file.FullName)
where fileText.Contains(searchTerm)
select file.FullName;
// Execute the query.
Console.WriteLine("The term \"{0}\" was found in:", searchTerm);
foreach (string filename in queryMatchingFiles)
{
Console.WriteLine(filename);
}
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
// Read the contents of the file.
static string GetFileText(string name)
{
string fileContents = String.Empty;
// If the file has been deleted since we took
// the snapshot, ignore it and return the empty string.
if (System.IO.File.Exists(name))
{
fileContents = System.IO.File.ReadAllText(name);
}
return fileContents;
}
}
The problem you're having is based on trying to load multiple gigabytes of text at the same time. If they're text files, you can stream them and just compare one line at a time.
var queryMatchingFiles =
from file in fileList
where file.Extension == ".htm"
let fileLines = File.ReadLines(file.FullName) // lazy IEnumerable<string>
where fileLines.Any(line => line.Contains(searchTerm))
select file.FullName;
I would suggest that you are getting an out of memory error because the way the query is written I believe that you will need to load the entire text of every file into memory and none of the objects can be released until the entire file set has been loaded. Could you not check for the search term in the GetFileText function and then just return a true or false?
If you did that the file text at least falls out of scope at the end of the function and the GC can recover the memory. It would actually be better to rewrite as a streaming function if you are dealing with large files/amounts then you could exit your reading early if you come across the search term and you wouldn't need the entire file in memory all the time.
Previous question on finding a term in an HTML file using a stream

How to check if a WPF resource exists?

I have an application, that reads a specific type of XML file. Those XML files can reference each other, e.g.:
<MyXml>
<Reference Path="pack://application:,,,/MyOtherXML.xml"/>
<!--More data-->
</MyXml>
This is mainly because they are quite long, and you don't want to repeat yourself with 180+ lines of XML.
However, I'm not sure how to check if the files exist if they are resources. I know that if they are normal files I can just use File.Exists, but I don't think you can do that for resources. I also found this, but the answer seems to be wrong. So how do you check if a resource exists on WPF?
You need to use GetManifestResourceStream to get resources and read collection of keys from the dictionary something like this -
public static string[] GetResourceNames()
{
var assembly = Assembly.GetExecutingAssembly();
string resName = assembly.GetName().Name + ".g.resources";
using (var stream = assembly.GetManifestResourceStream(resName))
{
using (var reader = new System.Resources.ResourceReader(stream))
{
return reader.Cast<DictionaryEntry>().Select(entry =>
(string)entry.Key).ToArray();
}
}
}
you can call Assembly.GetExecutingAssembly().GetManifestResourceNames() get all the resource names and check on the results for the resource you want
var names = Assembly.GetExecutingAssembly().GetManifestResourceNames();
if(names.Contains(resourceNameTosearch))
{
// exist
}

Categories

Resources