Check if xml exists in a directory and read it - c#

Hello everyone I'm new to c#. I want to read an xml file if it exists in a directory. 1) How can I read it? 2) If there are multiple xml files how to read those at the same time?
XmlTextReader xtr = new XmlTextReader(path)
string pathD = #"H:\UsersDirectory";
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] TXTFiles = di.GetFiles("*.xml");
if (TXTFiles.Length != 0)
{
//how can I read the file?
}

If you know the name of the file, you can use:
File.Exists("YourPath");
to check if the File exists. If not, you can use:
Directory.GetFiles("ContainingDirectory");
to get a list of all files in a directory, and then loop through them, checking if they end with .xml, to find your file.
As for reading the content of the file, you can use
File.ReadAllText("FilePath");
to read the content of your XML-File. For multiple files, you can obviously just call this function multiple times, once for every file.
If you want to edit XML too, I'd like to direct you towards XPathNavigator: https://learn.microsoft.com/en-us/troubleshoot/developer/visualstudio/csharp/language-compilers/xml-xpathnavigator

Related

checking if file exists in FileInfo[]

I am creating a Windows application in which on a button click it will check a folder specified in the .config file for '.SQL' files and if it has any files then the application will execute the SQL file in the specified DB.
So for checking the '.sql' file in a directory I used the below code:
DirectoryInfo d = new DirectoryInfo(path);
FileInfo[] sqlfiles = d.GetFiles("*.sql");
Now, I want to add an IF condition to check any such file exist, if not I want to place a warning message.
So could you please help me to find how to check whether any such '.sql' file exist in that directory using the above code?
You can use .Any() to check if any array, or list, or IEnumerable has items. IMO it's a much clearer intent than list.Count > 0.
DirectoryInfo d = new DirectoryInfo(path);
FileInfo[] sqlfiles = d.GetFiles("*.sql");
if(sqlFiles.Any())
{
// At least one .sql file exists
}
else
{
// No sql files exist
}
(Cue arguments about iterators etc.)

Read from a text file

I created a project and I want to read an array of strings from a .txt which is static. What is the right way to do that?
I created myfile.txt and put it in Asset folder of my project. Is it better to create a new folder? And then how can I read that file?
The easiest way to do so is by using
file3 = await localFolder.GetFileAsync(path);
IList<String> readFile = await Windows.Storage.FileIO.ReadLinesAsync(file3);
where path represents the file path or file name (depending on the location of the file)
It does not save it in an array as you wish but you can have the same functionality of arrays by utilizing lists. If you do not know how to utilize lists then there is more reason to use this method as practice and help you learn lists
You can read the file in various ways. Look at StreamReader for reading
See the docs:
using (StreamReader sr = new StreamReader("c:\\TestFile.txt"))
{
while (sr.Peek() >= 0)
{
Console.WriteLine(sr.ReadLine());
}
}
Note the need to escape a backslashes \ in path names if you don't use raw strings.

File's modification date in C#

I have to write an application, which will compare the modification date of two files. These files are Excel workbooks. The first file is located on a local drive and the second on a LAN network.
Any hints, how to write this app? There's no need to open these files, just to check the date from file attributes.
System.IO.FileInfo file1 = new System.IO.FileInfo(file1Name);
System.IO.FileInfo file2 = new System.IO.FileInfo(file2Name);
if(file1.LastWriteTime != file2.LastWriteTime)
//Do some stuff.
System.IO Namespace - FileInfo Class

Write to Specific line in text file C#

I have a web app that I am developing at work. I need to be able to take input data and append a text file after (x) number of lines.
My web app is using asp.net with c#
Can anyone help me please?
There's no way of "inserting" into a file in general - or of going to a specific line, without reading all the others, unless they're of a fixed size (in bytes).
Normally the approach would be something like:
Start writing a new file
Open the existing file
Copy the first x lines from the old file to the new one
Write the new line
Copy the remaining lines from the old file to the new one
Move the old one to a backup file
Move the new file to the old name
Delete the backup file
(This ensures that at any one point there's at least the old file in some form. You can make it slightly simpler if you just delete the old file and then move the new one into place.)
Don't forget to ensure this is synchronized appropriately - you don't want to have two copies of this algorithm running at the same time...
EDIT: If you've got XML files, then I'd suggest usually just loading it into the DOM (e.g. with LINQ to XML), making the change, and then saving it out again. Don't treat it just like an unstructured text file.
You could potentially make this more efficient using XmlReader and XmlWriter - but you're certainly going to have to read the whole original file and write out the new file. Have you benchmarked simple code and found it too slow? How often are you doing this? How big are the files?
I would suggest finding another strategy, specifically a relational database management system. A text file lives on the file system and does not support concurrent access like a good (read:not Access) database. A web application does support concurrent requests. Once you have more than one user working at the same time, your app will experience IO Exceptions.
OK - Thanks to your help Jon I have figured it out.
FileInfo fi = new FileInfo(Server.MapPath("~/Playlists/" + user + "/" + ListBox1.SelectedItem.Text + ".wpl"));
XmlDocument originalXML = new XmlDocument();
originalXML.Load(fi.FullName);
XmlWriter newXML = XmlWriter.Create(Server.MapPath("~/Playlists/" + user + "/" + ListBox1.SelectedItem.Text + ".wpl"));
XmlNode smil = originalXML.SelectSingleNode("smil/body/seq");
XmlNode media = originalXML.CreateNode(XmlNodeType.Element, "media", null);
XmlAttribute src = originalXML.CreateAttribute("src");
DirectoryInfo di = new DirectoryInfo(Server.MapPath("~" + folder));
foreach (FileInfo file in di.GetFiles("*", SearchOption.AllDirectories))
{
string path = file.FullName;
path = path.Replace(#"F:\Music\Music by Artist", "http://bgab-mor01-n/Music");
path = path.Replace(#"\", "/");
path = path.Replace(",", "");
path = path.Replace("'", "");
path = path.Replace("&", "");
if (file.Extension == ".mp3" || file.Extension == ".wma" || file.Extension == ".MP3")
{
src.Value = path;
media.Attributes.Append(src);
smil.AppendChild(media);
}
}
originalXML.Save(newXML);
newXML.Close();
I really couldn't have done it without you. You are the man. Thanks for everything.

C# - Autozip files in a folder based on Year-Month

IT has been tasked with reducing the file-server usage rate so I'd like to do my part my compressing old files(ie Excel/Access/Txt).
We have some folders that contain thousands of files so I don't want to just zip the whole directory into one large file - it would be preferrable to have a number of smaller files so that it would be easier for a user to find the data 'bucket' they are looking for.
Is there a way using C# to read through a directory and zip the files into year-month groups (all files from year-month placed together in one zip)?
Or would it be better to use a script like AutoIT?
Or are there programs already existing to do this so I don't have to code anything?
Im not sure if your question is about zipping, selecting files from particular year/month or both.
About zipping Peter already mentioned 7-zip and SharpZipLib. I have personally only experience with the latter but its all positive, easy to work with.
About grouping your files it could be done by iterating all the files in the folder and group them by either there created date or last modified date.
pseudo:
var files = new Dictionary<DateTime, IList<string>>();
foreach (var file in Directory.GetFiles(...)) {
var fi = new FileInfo(file);
var date = fi.CreatedDate();
var groupDate = new DateTime(date.Year, date.Month);
if (!files.ContainsKey(groupDate)) files.Add(groupDate, new Collection<string>());
files[groupDate].Add(file);
}
now your should have a dictionary containing distinct year/month keys and foreach key a list of files belonging to that group. So for zipping
pseudo:
foreach (var entry in files) {
var date = entry.Key;
var list = entry.Value;
// create zip-file named date.ToString();
foreach (var file in list) {
// add file to zip
}
}
Surely you can do this with a bit of C# and libraries like 7-zip or SharpZipLib.
You could use System.IO.Directory.GetFiles() to loop through the files on each directory, parsing out by file name and adding them to a 7-zip or SharpZipLib object. If it's thousands of files it might be best to throw it in a service or some kind of scheduled task to run overnight so as not to tax the fileshare.
Good luck to you !
EDIT: As an addendum you could use a System.IO.FileInfo object for each file if you need to parse by created date or other file attirbutes.

Categories

Resources