C# How do I write a variable to a file? [duplicate] - c#

This question already has answers here:
How to save a List<string> on Settings.Default?
(4 answers)
Saving from List<T> to txt
(7 answers)
Closed 7 years ago.
I'm new to C# and I'm trying to make a List persist when relaunching the application. Everywhere I go I can't seem to find a simple way to do this, something like Python's Pickle. Any help would be appreciated thank you.

The answer to this really depends on what exactly you want to save. Is it an actual List, as in List<> obejct? What does it contain? If it's something simple such as a List< string >, then do
var list = new List<string>();
list.Add("HELLO");
list.Add("hi");
// save
using (var fs = new FileStream(#"F:\test.xml", FileMode.Create))
{
var serializer = new XmlSerializer(typeof(List<string>));
serializer.Serialize(fs, list);
}
// read
using (var s = new FileStream(#"F:\test.xml", FileMode.Open))
{
var serializer = new XmlSerializer(typeof(List<string>));
List<string> result = (List<string>)serializer.Deserialize(s);
}

Related

How to find duplicate keys from a List<KeyValuePair<byte[], string>> fileHashList = new List<KeyValuePair<byte[], string>>(); [duplicate]

This question already has answers here:
Group by array contents
(1 answer)
Easiest way to compare arrays in C#
(19 answers)
Closed 2 years ago.
I've a lsit of type List<KeyValuePair<byte[], string>> fileHashList = new List<KeyValuePair<byte[], string>>();
foreach (string entry in results)
{
FileInfo fileInfo = new FileInfo(Path.Combine("DirectoryPath"), entry));
using (var md5 = MD5.Create())
{
using (var stream = File.OpenRead(fileInfo.FullName))
{
var hash = md5.ComputeHash(stream);
fileHashList.Add(new KeyValuePair<byte[], string>(hash, fileInfo.FullName));
}
}
}
I need to find all the duplicate keys in this list.
I tried this but doesn't work in my case, I get "Enumeration yielded no results" even though I've same keys!
Let me know if any additional data is needed
Thanks

CsvHelper - Split output files [duplicate]

This question already has answers here:
Split a List into smaller lists of N size [duplicate]
(21 answers)
Closed 3 years ago.
I'm using Csv Helper to write out a Linq Query with million of rows. I would like to split the output by, for instance, 1 million of rows each. Could I do that or should I use other type of writting method?
Here is my code:
var _path = UniversalVariables.outputCsvFiles + "entire_output.csv";
var pvQuery = from car in Cars
select car;
if (!Directory.Exists(UniversalVariables.outputCsvFiles))
{
Directory.CreateDirectory(UniversalVariables.outputCsvFiles);
}
using (var sw = new StreamWriter(_path))
using (var csv = new CsvWriter(sw))
{
csv.Configuration.Delimiter = UniversalVariables.csvDelimiter;
csv.Configuration.HasHeaderRecord = true;
csv.WriteHeader<Car>();
csv.NextRecord();
csv.WriteRecords(pvQuery);
sw.Flush();
}
You could use Linq to split the collection in to sub collections (chunks of size n). For example
pvQuery.Select((x,index)=>new {Value=x,Index=index})
.GroupBy(x=>(int)(x.Index/numberOfItemsPerGroup))
.Select(x=>x.Select(c=>c.Value));
Making it a Extension method
static class Extensions
{
public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> source, int numberOfItemsPerGroup)
{
return source.Select((x,index)=>new {Value=x,Index=index})
.GroupBy(x=>(int)(x.Index/numberOfItemsPerGroup))
.Select(x=>x.Select(c=>c.Value));
}
}
Client code
SourceCollection.Split(numberOfItemsPerGroup);

How to update documents on the Mongo side? [duplicate]

This question already has answers here:
MongoDB: Updating documents using data from the same document [duplicate]
(6 answers)
Closed 6 years ago.
const string Pattern = #"(?si)<([^\s<]*totalWork[^\s<]*)>.*?</\1>";
var filter = Builders<JobInfoRecord>.Filter.Regex(x => x.SerializedBackgroundJobInfo,
new BsonRegularExpression(Pattern, "i"));
var documents = await records.Find(filter).ToListAsync();
====
After I get documents I working with each document on the my side.
const string EmptyTag = "<$1></$1>";
var updatedJobInfo = Regex.Replace(document.SerializedBackgroundJobInfo, Pattern, EmptyTag);
How can I do Regex.Replace in the mongo side? Or that can only happen in the client?
Is the following Replace works in the Mongo side?
using (var cursor = await jobInfoDocuments.FindAsync<JobInfoRecord>(filter))
{
while (await cursor.MoveNextAsync())
{
var batch = cursor.Current;
foreach (var document in batch)
{
var newInfo = Regex.Replace(document.SerializedBackgroundJobInfo, regex, EmptyTag);
// Applying several operations within the one request.
operationList.Add(new UpdateOneModel<JobInfoRecord>(Builders<JobInfoRecord>.Filter.Eq("_id", document.JobId),
Builders<JobInfoRecord>.Update.Set("SerializedBackgroundJobInfo", newInfo)));
}
You can do it with javascript but be sure the fix the filter to work with mongo shell
db.records.find(filter).forEach(function (doc) {
var pattern = /<([^\s<]*totalWork[^\s<]*)>[\s\S]*?</\1>/i;
var EmptyTag = "<$1></$1>";
doc.SerializedBackgroundJobInfo = doc.SerializedBackgroundJobInfo.replace(pattern, EmptyTag);
db.records.save(doc);
})

Can I see the contents of the String Table in a running process? [duplicate]

This question already has answers here:
Read the content of the string intern pool
(2 answers)
Closed 7 years ago.
Is there any way I can see the contents of the string table in a running .NET application?
I want to compare a console application with vanilla string concatinations and one using the string builder.
You can use ClrMD to attach to a process and retrieve information from it. Something along the lines of the following should work:
var proc = Process.GetProcessesByName("myapp.exe").FirstOrDefault();
using (var target = DataTarget.AttachToProcess(proc.Id, 1000))
{
var runtime = target.ClrVersions[0].CreateRuntime();
var heap = runtime.GetHeap();
foreach (var obj in heap.EnumerateObjectAddresses())
{
var type = heap.GetObjectType(obj);
if (type.Name == "System.String")
{
var value = (string)type.GetValue(obj);
// Write value to disk or something.
}
}
}

Adding elements to List<> doesn't work [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
I have a List<> declared, which is accessable in the whole class
List<article> data;
Now I'm using a method to fill the List<>:
StreamReader sr = new StreamReader(filePath);
while (!sr.EndOfStream)
{
string[] Line = sr.ReadLine().Split(';');
article newArticle = new article();
newArticle.articleNumber = Line[0];
newArticle.description = Line[1];
newArticle.articleId = Line[2];
try
{
data.Add(newArticle);
}
catch(NullReferenceException ex)
{
// Nothing to do here
}
}
Each time, the loop repeats, the newArticle-Object contains all his elements, so it is definetely not null.
But it doesn't add to the data-List<>.
What am I missing?
In order to add items to the list, you must first initialise it.
Replace:
List<article> data;
with:
List<article> data = new List<article>();

Categories