Read from a text file - c#

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.

Related

Check if xml exists in a directory and read it

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

Getting the contents of a file in Visual Studio without opening the file from an extension

I'm trying to read the contents of a file in a Visual Studio extension. The following code works, but forces me to open the file, if it isn't (otherwise it crashes):
textDocument = (TextDocument)projectItem.Document.Object("TextDocument");
EditPoint editPoint = textDocument.StartPoint.CreateEditPoint();
string text = editPoint.GetText(textDocument.EndPoint);
I can get the path of the project, so I suppose I could make an educated guess as to the location of the project item. However, ideally I'd like to either get the file contents without opening it; or, alternatively, get the path to the project item (then I could just use System.IO to access the file contents).
I've looked, but don't seem to be able to find any mention of either of these. Can anyone point me in the right direction, please?
You can get the path from a ProjectItem by reading its properties.
var path = YourProjectItem.Properties.Item("FullPath").Value.ToString()
After you have the path you can read its content with System.IO.
string content = File.ReadAllText(path);
If the file is somewhat larger and you are getting troubles with the current code due to size, you should take a look at the StreamReader class.
I'm not sure if this is possible for extensions but you could probably use System.IO, like this:
using System.IO;
string filePath = #"C:\Whatever\YourFileName.txt";
string fileText = File.ReadAllText(filePath);
You could also use StreamReader like this:
using System.IO;
string filePath = #"C:\Whatever\YourFileName.txt";
using (StreamReader sr = new StreamReader(filePath))
fileText = sr.ReadToEnd();
EDIT:
I think I understand you better now.
The only way to "get the file contents without opening it" would be if the extension were to give you that data actively, but I can safely assume it doesn't.
When reading a file, you should already know where the file is (if you don't know then either you're not intended to access that file or you just haven't looked long enough).
I'd try searching the SDK files manually (Or with a file crawler).

How can I use json inside my resources folder?

I'm using Visual Studio with Xamarin and wish to store a json file inside of my resources folder.
I need to get the path, deserialize it, then load the data asynchronously. I've looked around, but can't find any useful examples. Is this possible?
Put the file under the "Assets" folder and use the following code to access it:
// to read from assets folder
string content;
AssetManager assets = this.Assets;
using (StreamReader sr = new StreamReader (assets.Open ("file.json")))
{
content = sr.ReadToEnd ();
}
// JSON is now in "content"
Afterwards you can pass the string to a JSON parser. You can find more information on this topic in the Xamarin documentation (=> Reading assets).

Read .txt embedded as resource

I have embedded a resource into my code, I want to read the text and apply the text to some string variables. I have worked out how to do that when I use an external file but I only want the .exe
string setting_file = "config.txt";
string complete = File.ReadAllText(setting_file);
string Filename = complete.Split('#').Last(); //"Test.zip";
string URL = complete.Split('#').First();
How can I read the resource config.txt
(Preferably without new procedures)
The File class is only used for accessing the file system whereas your file is no longer in the system so this line needs to change. As others have hinted with linked answers you need to get the stream for the resource and then read that. The below method can be called to replace your File.ReadAllText method call.
private static string GetTextResourceFile(string resourceName)
{
var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName);
using (var sr = new StreamReader(stream))
{
return sr.ReadToEnd();
}
}
The resourceName will be something along the lines of MyNamespace.Myfile.txt. If you are having problems finding your resourcename then the method GetManifestResourceNames on the assembly will help you identify it while debugging.
Also of note is the above method will throw an exception if the resource isn't found. This should be handled in real code but I didn't want to confuse the above sample with standard error handling code.
See also How to read embedded resource text file for a different question with the same answer (that differs in that it asks only about streams but in fact streams seem to be the only way to access embedded resource files anyway).
This is how you can use embedded files Properties.Resources.yourfilename

zipping with c#

i am trying to use GZipStream to create a gz file using c#.
my problem is that i have a list that contains strings. and i need to create a password protected zip file, and put in it a text file containing the strings.
i don't want to create the textfile, then zip it, and then delete the textfile. i want to directly create a password protected zip file that contains the text file.
any help?
EDIT: i am done with the zipping stuff. now i need to set a pass for the created zip file. any help?
You should consider using SharpZipLib. It's an open source .net compression library. It includes examples on how to create either a .gz or a .zip file. Note that you can write directly to the .zip file. You don't need to create an intermediate file on disk first.
Edit: (in response to your edit) SharpZipLib supports zip passwords too.
Just create a StreamWriter wrapping your GZipStream, and write text to it.
GZipStream can be used to create a .gz file, but this is not the same as a .zip file.
For creating password-protected zip files, I think you need to go to a third-party library.
Here's how to do it using DotNetZip...
var sb = new System.Text.StringBuilder();
sb.Append("This is the text file...");
foreach (var item in listOfStrings)
sb.Append(item);
// sb now contains all the content that will be placed into
// the text file entry inside the zip.
using (var zip = new Ionic.Zip.ZipFile())
{
// set the password on the zip (implicitly enables encryption)
zip.Password = "Whatever.You.Like!!";
// optional: select strong encryption
zip.Encryption = Ionic.Zip.EncryptionAlgorithm.WinZipAes256;
// add an entry to the zip, specify a name, specify string content
zip.AddEntry("NameOfFile.txt", sb.ToString());
// save the file
zip.Save("MyFile.zip");
}

Categories

Resources