WP7 Isolated Storage Text Document Read Line - c#

Is there a way using Isolated storage ie a Text document, to grab the text on a certain line.
I would like to save variables to a text document on my settings page of my app. Then go back to the main page and read the variable saved on line 3. I already know how to save them. just not read certain lines.
Also is the text document created by my app going to still be there if i close and reopen the app?

Try this
using( TextReader reader = new StreamReader(
new IsolatedStorageFileStream( "myFile.txt", System.IO.FileMode.Open,
IsolatedStorageFile.GetUserStoreForApplication() ) ) {
string line = reader.ReadLine(); // first line, discard
line = reader.ReadLine(); // second line, discard
line = reader.ReadLine(); // third line, read the variable value
}
However, you might be better off using the IsolatedStorageSettings class to store settings (the link contains example usage). Another option is to put all your settings into a serializable class and use an XmlSerializer to save / read the settings. Both these approaches would not require parsing the file manually.

Related

Best approach to replace specific lines in a text file in c#

For the following operation:
Open a text file
Search and replace all searching characters with new characters
I'd like to achieve above in c#, here is my code:
using (StreamReader sr = new StreamReader(#"S:\Personal Folders\A\TESTA.txt"))
{
using (StreamWriter sw = new StreamWriter(#"S:\Personal Folders\A\TESTB.txt"))
{
string line;
while ((line = sr.ReadLine())!= null)
{
if (!line.Contains("before"))
{
sw.WriteLine(line);
}
else if (line.Contains("before"))
{
sw.WriteLine(line.Replace("before", "after"));
}
}
}
}
Basically, the above code will generate a new file with the desired replace operation, but as you can see, the way I am doing is read each line of the original file and write to a new file. This could achieve my goal, but it may have system IO issue because it is reading and writing for each line. Also, I cannot read all the lines to an array first, and then write, because the file is large and if I try to write to an string[], replace all, then write the array to the file, will bring about the memory timeout issue.
Is there any way that I can just locate to the specific lines, and just replace those lines and keep all the rest? Or What is the best way to solve the above problem? Thanks
I don't know what IO issue you are worried about, but your code should work ok. You can code more concisely as follows:
using (StreamReader sr = new StreamReader(#"S:\Personal Folders\A\TESTA.txt"))
{
using (StreamWriter sw = new StreamWriter(#"S:\Personal Folders\A\TESTB.txt"))
{
while ((string line = sr.ReadLine())!= null)
{
sw.WriteLine(line.Replace("before", "after"));
}
}
}
This will run a bit faster because it searches for "before" only once per line. By default the StreamWriter buffers your writes and does not flush to the disk each time you call WriteLine, and file IO is asynchronous in the operating system, so don't worry so much about IO.
In general, what you are doing is correct, possibly followed by some renames to replace the original file. If you do want to replace the original file, you should rename the original file to a temporary name, rename the new file to the original name, and then either leave or delete the original file. You must handle conflicts with your temporary name and errors in all renames.
Consider you are replacing a six character string with a five character string - if you write back to the original file, what will you do with the extra characters? Files are stored on disk as raw bytes of data, there is no "text" file on disk. What if you replace a string with a longer one - you then potentially have to move the entire rest of the file to make room to write the longer line.
You can imagine the file on disk as letters written on graph paper in the boxes. The end of each line is noted by a special character (or characters - in Windows, that is CRLF), the characters fill all the boxes horizontally. If you tried to replace words on the graph paper you would have to erase and re-write lots of letters. Writing on a new sheet will be easiest.
Well, your approach is basically fine... but I wouldn't check if the line contains the word before... the trade-off is not good enough:
using (StreamReader sr = new StreamReader(#"S:\Personal Folders\A\TESTA.txt"))
{
using (StreamWriter sw = new StreamWriter(#"S:\Personal Folders\A\TESTB.txt"))
{
String line;
while ((line = sr.ReadLine()) != null)
sw.WriteLine(line.Replace("before", "after"));
}
}
Try following :
else if (line.Contains("before"))
{
sw.WriteLine(line.Replace("before", "after"));
sw.Write(sr.ReadToEnd());
break;
}

Save dynamic variables in text file without closing it using C#

I need to save six dynamic variables in a text file as fast as possible in a way that if the power is turned off (or application is killed), I can have access to the last saved version of the variables all together (not just some of the variables).
Writing these six variables in registry takes ~0.1 ms which is good. However I'd rather avoid modifying the registry.
I tried StreamWriter like this in a backgroundworker loop:
System.IO.StreamWriter file = new System.IO.StreamWriter("test.txt", false);
file.Write("Comma Separated Version of Variables in String");
file.Flush();
file.Close();
It takes more that 1 ms which is slow for my application! So, I removed first and last line out of the loop:
System.IO.StreamWriter file = new System.IO.StreamWriter("test.txt", false);
while (true)
{
file.Write("Comma Separated Version of Variables in String");
file.Flush();
}
file.Close();
It is now excellent (~0.007 ms)! However, it appends the new strings to the file. How I can overwrite the first line of the text file (it has only one line) without closing it?
EDIT: I also tried WriteAllTextwhich works but it is like 15 times slower that the above code!
Set position of the stream to 0.
while (true)
{
file.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);
file.WriteLine("Comma Separated Version of Variables in String");
file.Flush();
}

What is the file path for references added in Content project in XNA?

This problem is somewhat similar to this.
In my case, I have a text file. And since there is no content importer that works for text file, I have to write my own functions using stream readers. What I am trying to accomplish is to read from the text file, and set a few values accordingly into the options screen. I have added all necessary references, but using "../options.txt" as filepath does not work. Quite possibly the filepath is resolved to something else than Content folder. How do I then proceed with it?
Also, I am getting errors saying "attempt to access method (System.IO....ctor) failed". Is it that I am missing to add some other reference?
Does this have to work on the xBox 360? If so it's not possible to just use the filesystem like you can in Windows, you'll need to use a storage device. To be honest I would just use this method anyway so if you decide to take your game on to WP7 or 360 it'll just work.
There is a nice demo game that loads and saves data on this Microsoft page as well as a description of what it's doing
This is taken from the demo, it shows how to open a storage container and serialize some config data to it, the load operation is just as simple.
// Create the data to save.
SaveGameData data = new SaveGameData();
data.PlayerName = "Hiro";
data.AvatarPosition = new Vector2(360, 360);
data.Level = 11;
data.Score = 4200;
// Open a storage container.
IAsyncResult result =
device.BeginOpenContainer("StorageDemo", null, null);
// Wait for the WaitHandle to become signaled.
result.AsyncWaitHandle.WaitOne();
StorageContainer container = device.EndOpenContainer(result);
// Close the wait handle.
result.AsyncWaitHandle.Close();
string filename = "savegame.sav";
// Check to see whether the save exists.
if (container.FileExists(filename))
// Delete it so that we can create one fresh.
container.DeleteFile(filename);
// Create the file.
Stream stream = container.CreateFile(filename);
// Convert the object to XML data and put it in the stream.
XmlSerializer serializer = new XmlSerializer(typeof(SaveGameData));
serializer.Serialize(stream, data);
// Close the file.
stream.Close();
// Dispose the container, to commit changes.
container.Dispose();

How to store formatted snippets of Microsoft Word documents in sql server

I need to extract formatted text snippets of a Word document and store it inside an SQL Server table, for later processing and then reinsertion in the Word document using C#.
I've had a look at the Word DOM and it seems that I need to use a combination of the Document.Load(), Document.Save() and Range.Copy(), Range.Paste() methods to create a file for each snippets that I then load into the DB.
Isn't there a easier (more efficient way)?
By the way the code snippets can be hidden text and I was thinking about storing the snippets as RTF.
Finally I got to use Aspose.Words for .NET to extract the code snippets from the Word file I'm interested in and store them as RTF:
// Get insteresting code snippets (in this case text runs with
// style "tw4winMark")
Document sourceDocument = new Document(fileName);
var runs = sourceDocument.GetChildNodes(NodeType.Run, true)
.Select(r => r.Font.StyleName == "tw4winMark").ToList();
// Store snippets into temporary document
// Read Aspose documentation for details
Document document = new Document();
if (runs.Count > 0) {
NodeImporter nodeImporter = new NodeImporter(
runs[0].Document,
document,
ImportFormatMode.KeepSourceFormatting
);
foreach (Run run in runs) {
Run importedRun = nodeImporter.ImportNode(run, true) as Run;
importedRun.Font.Hidden = false;
document.Sections[0].Body.Paragraphs[0].AppendChild(importedRun);
}
}
// save temporary document in MemoryStream as RTF
RtfSaveOptions saveOptions = new RtfSaveOptions();
MemoryStream ms = new MemoryStream();
document.Save(ms, saveOptions);
// retrieve RTF from MemoryStream
ms.Seek(0, SeekOrigin.Begin);
StreamReader sr = new StreamReader(ms);
string rtf = sr.ReadToEnd();
One can then store the rtf into a text field of the database as usual and edit it in a RTF text control.
Document.load, then select the range via a RANGE object, then use the XML property of the range object to get the XML of that range and store it.
You can later insert the XML into another document using the reverse process.
Editing the snippets might prove interesting though, because I'm not aware of any web based WORD compatible editors.

How to compare two TXT files before send it to SQL

I have to handle TXT dat files which coming from one embed device, My problem is in that device always sending all captured data but I want to take only difrences between two sending and do calculation on them. After calculation I send it to SQL using bulkinsert function. I want to extract data which is different according to first file I got from device. Lats say that device first time device send data like this in some.dat (ASCII) file
0000199991
0000199321
0000132913
0000232318
0000312898
On second calls to get data from device it is going to return all again (previous and next captured records) something like this
0000199991
0000199321
0000132913
0000232318
0000312898
9992129990
8782999022
2323423456
But this time I do want only to calculate and pass trough data added after first insert.
I am trying to make Win Forms app using C# and Visual Studio 2008
You can do this using LINQ:
string[] addedLines = File.ReadAllLines(secondPath)
.Except(File.ReadAllLines(firstPath))
.ToArray();
Note that this will be slow for large files.
For large files, replace ReadAllLines with the following method: (In .Net 4, you can use File.ReadLines instead)
static IEnumerable<string> EnumerateLines(string path) {
using(var reader = File.OpenText(path)) {
string line;
while(null != (line = reader.ReadLine())
yield return line;
}
}
Would this work for you?
string dataAddedAfterFirstInsert = secondString.SubString(firstString.Length, secondString.Length)
One option would be to remember the filesize each time you receive the file, then when you get the new file you can immediately move the file pointer to the position in the file that corresponds to the end of the previous file and read from that point on.
Here is a rough outline of the idea
long lastPosition = GetLastFilePositionFromDatabase();
using (FileStream fs = new FileStream(...))
{
// Seek to the last position, this is zero the first time
fs.Seek(lastFilePosition, SeekOrigin.Begin);
// Process your file from the current position
ProcessFile(fs);
// Once you reach the end of the file, save this position so
// for use with the next file
SaveLastFilePositionToDatabase(fs.Position);
}

Categories

Resources