Load in an unknown number of files in a specific directory - c#

I'm trying to load an unknown number of json files in a directory using json.net (C:/users/Nathan/Documents/test)
I want to be able to add json files to this directory and no matter how many there are my program should be able to access all of them and load them as separate a jObject with unique names.
Is this even possible?
Edit I don't have code yet, I have to get ideas what direction to take for this.

Code would be something like below:
var fileNames = Directory.GetFiles(#"C:\user\Nathan\Documents\test");
foreach(var file in fileNames)
{
using (var sr = File.OpenText(file))
using (var reader = new JsonTextReader(sr))
{
var json = (JObject) JToken.ReadFrom(reader);
}
}

Use string[] fileNames = Directory.GetFiles("C:/users/Nathan/Documents/test") to get all the file names in a specific directory. Also, this can throw an exception if the directory does not exist.

Related

XML file from ZIP Archive is incomplete in C#

I've work with large XML Files (~1000000 lines, 34mb) that are stored in a ZIP archive. The XML file is used at runtime to store and load app settings and measurements. The gets loadeted with this function:
public static void LoadFile(string path, string name)
{
using (var file = File.OpenRead(path))
{
using (var zip = new ZipArchive(file, ZipArchiveMode.Read))
{
var foundConfigurationFile = zip.Entries.First(x => x.FullName == ConfigurationFileName);
using (var stream = new StreamReader(foundConfigurationFile.Open()))
{
var xmlSerializer = new XmlSerializer(typeof(ProjectConfiguration));
var newObject = xmlSerializer.Deserialize(stream);
CurrentConfiguration = null;
CurrentConfiguration = newObject as ProjectConfiguration;
AddRecentFiles(name, path);
}
}
}
}
This works for most of the time.
However, some files don't get read to the end and i get an error that the file contains non valid XML. I used
foundConfigurationFile.ExtractToFile();
and fount that the readed file stops at line ~800000. But this only happens inside this code. When i open the file via editor everything is there.
It looks like the zip doesnt get loaded correctly, or for that matter, completly.
Am i running in some limitations? Or is there an error in my code i don't find?
The file is saved via:
using (var file = File.OpenWrite(Path.Combine(dirInfo.ToString(), fileName.ToString()) + ".pwe"))
{
var zip = new ZipArchive(file, ZipArchiveMode.Create);
var configurationEntry = zip.CreateEntry(ConfigurationFileName, CompressionLevel.Optimal);
var stream = configurationEntry.Open();
var xmlSerializer = new XmlSerializer(typeof(ProjectConfiguration));
xmlSerializer.Serialize(stream, CurrentConfiguration);
stream.Close();
zip.Dispose();
}
Update:
The problem was the File.OpenWrite() method.
If you try to override a file with this method it will result in a mix between the old file and the new file, if the new file is shorter than the old file.
File.OpenWrite() doenst truncate the old file first as stated in the docs
In order to do it correctly it was neccesary to use the File.Create() method. Because this method truncates the old file first.

Get a Json file from a specific folder and serialize it

I need to get json file from a specific folder in my solution. the name of the json file is "plaza.json" and the folder it is in is Data. Please see image below.
How do I get this file and serialize it? I have searched for some answers but the closest is this:
using (var streamReader = new StreamReader("plaza.json"))
{
string json = streamReader.ReadToEnd();
var deserializedObject = JsonConvert.DeserializeObject<SomeClass>(json);
}
if I use that, it doesn't see my json file
using (var streamReader = new StreamReader(Server.MapPath("~/Data/plaza.json"))
{
string json = streamReader.ReadToEnd();
var deserializedObject = JsonConvert.DeserializeObject<SomeClass>(json);
}
This should work, haven’t test but check this how file will be accessed
Depending on you project type it can be server.mappath or hostingenvironment.mappath
If desktop app like win forms or wpf use this
Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"Data/plaza.json");
Make sure to put copy file if modified property in build property

Enumerate zipped contents of unzipped folder

I am trying to enumerate the zipped folders that are inside an unzipped folder using Directory.GetDirectories(folderPath).
The problem I have is that it does not seem to be finding the zipped folders, when I come to iterate over the string[], it is empty.
Is Directory.GetDirectories() the wrong way to go about this and if so what method serves this purpose?
Filepath example: C:\...\...\daily\daily\{series of zipped folder}
public void CheckZippedDailyFolder(string folderPath)
{
if(folderPath.IsNullOrEmpty())
throw new Exception("Folder path required");
foreach (var folder in Directory.GetDirectories(folderPath))
{
var unzippedFolder = Compression.Unzip(folder + ".zip", folderPath);
using (TextReader reader = File.OpenText(unzippedFolder + #"\" + new DirectoryInfo(folderPath).Name))
{
var csv = new CsvReader(reader);
var field = csv.GetField(0);
Console.WriteLine(field);
}
}
}
GetDirectories is the wrong thing to use. Explorer lies to you; zip files are actually files with an extension .zip, not real directories on the file system level.
Look at:
https://msdn.microsoft.com/en-us/library/system.io.compression.ziparchive.entries%28v=vs.110%29.aspx (ZipArchive.Entries) and/or
https://msdn.microsoft.com/en-us/library/system.io.compression.zipfile%28v=vs.110%29.aspx (ZipFile) to see how to deal with them.

Loop through Embedded Resources and copy to local path

I have a simple WinForms application, but it has some Embedded Resources (in a subfolder under "Resources") that I would like to copy out to a folder on the computer. Currently, I have the latter working (with a explicit method naming the Embedded Resource and where it should go):
string path = #"C:\Users\derek.antrican\";
using (Stream input = Assembly.GetExecutingAssembly().GetManifestResourceStream("WINFORMSAPP.Resources.SUBFOLDER.FILE.txt"))
using (Stream output = File.Create(path + "FILE.txt"))
{
input.CopyTo(output);
}
But I'm still trying to figure out how to get the former working: looping through all the resources in the "WINFORMSAPP.Resources.SUBFOLDER" folder and moving them. I've done quite a bit of Googling, but I'm still not sure how to get a list of each Embedded Resource in this subfolder.
Any help would be GREATLY appreciated!
Start by getting all resources embedded in your assembly:
Assembly.GetExecutingAssembly().GetManifestResourceNames()
You can check these names against the name of your desired subfolder to see if they are inside or outside it with a simple call to StartsWith.
Now loop through the names, and get the corresponding resource stream:
const string subfolder = "WINFORMSAPP.Resources.SUBFOLDER.";
var assembly = Assembly.GetExecutingAssembly();
foreach (var name in assembly.GetManifestResourceNames()) {
// Skip names outside of your desired subfolder
if (!name.StartsWith(subfolder)) {
continue;
}
using (Stream input = assembly.GetManifestResourceStream(name))
using (Stream output = File.Create(path + name.Substring(subfolder.Length))) {
input.CopyTo(output);
}
}

Adding to listbox from multiple files and deleting doubled items

As you can read in the title, I am trying to add listbox items to a listbox from multiple files. But I don't know how to read from all these files and how to delete the doubled lines (as some txt-files contain the same information).
A new file gets added every day, so I can't just read them all manually.
My code so far:
string directory = System.AppDomain.CurrentDomain.BaseDirectory;
DirectoryInfo dinfo = new DirectoryInfo(directory);
FileInfo[] Files = dinfo.GetFiles("*.txt");
First of all you need to identify every file you need to read.
Once you have all the files you need to read the data from each file into some form of storage for example a DataTable.
Once you have filled the DataTable you will need to populate the ListBox with the data.
From what you've got so far it looks like your next step will be to collect the data from each of the files (we can deal with removing duplicates afterwards).
So perhaps:
HashSet<something> myCollection = new HashSet<something>();
// perhaps <something> is just a string?
foreach (var file in Files)
{
// Collect what you need and pop it in the collection
}
// Remove duplicates
To get the info out of the files you'll probably need a StreamReader.
Fore removal of duplicates try HashSets.
you can try this code:
in this code all unique data will be stored in lstData and you can bind your control using this
string directory = System.AppDomain.CurrentDomain.BaseDirectory;
DirectoryInfo dinfo = new DirectoryInfo(directory);
FileInfo[] Files = dinfo.GetFiles("*.txt");
List<string> lstData = new List<string>();
foreach (var file in Files)
{
using (StreamReader sr = File.OpenText(file.FullName))
{
string s = String.Empty;
while ((s = sr.ReadLine()) != null)
{
if (!lstData.Contains(s))
{
lstData.Add(s);
}
}
}
}

Categories