How to write into an existing textfile in windows phone? - c#

If this is the code in opening a textfile "word.txt" in my solution explorer.
Stream txtStream = Application.GetResourceStream(new Uri("/sample;component/word.txt", UriKind.Relative)).Stream;
using (StreamReader sr = new StreamReader(txtStream))
{
string jon;
while (!sr.EndOfStream)
{
jon = sr.ReadLine();
mylistbox.ItemSource = jon;
}
}
How do i write and append in the existing textfile?

Here is an example
public static void WriteBackgroundSetting(string currentBackground)
{
const string fileName = "RecipeHub.txt";
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if(myIsolatedStorage.FileExists(fileName))
myIsolatedStorage.DeleteFile(fileName);
var stream = myIsolatedStorage.CreateFile(fileName);
using (StreamWriter isoStream = new StreamWriter(stream))
{
isoStream.WriteLine(currentBackground);
}
}
}

Related

Could not find a part of the path (Write file html)

I need to create html file and save to drive C:/TMP after i public it error
Could not find a part of the path 'C:\TMP\test.html'
I have the following code
string fileName = #"C:\\TMP\\test.html";
using (FileStream fs = File.Create(fileName))
{
using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
{
w.WriteLine("<!DOCTYPE html>");
w.WriteLine("<html>");
w.WriteLine("<head>");
w.WriteLine("<title>PChart</title>");
w.WriteLine("</p>");
w.WriteLine("</body>");
w.WriteLine("</html>");
}
}
Are you sure the directory exists ? Put Directory.CreateDirectory in our code:
string fileName = #"C:\\TMP\\BlaBla\\test.html";
Directory.CreateDirectory(Path.GetDirectoryName(fileName));
using (FileStream fs = File.Create(fileName))
{
using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
{
w.WriteLine("<!DOCTYPE html>");
w.WriteLine("<html>");
w.WriteLine("<head>");
w.WriteLine("<title>PChart</title>");
w.WriteLine("</p>");
w.WriteLine("</body>");
w.WriteLine("</html>");
}
}
I tested, for me it works
Hi pls try using below code. If there is no file It will create. But path should be correct.
string path = #"D:\\TMP\\test.html";
using (StreamWriter w = System.IO.File.AppendText(path))
{
w.WriteLine("<!DOCTYPE html>");
w.WriteLine("<html>");
w.WriteLine("<head>");
w.WriteLine("<title>PChart</title>");
w.WriteLine("</p>");
w.WriteLine("</body>");
w.WriteLine("</html>");
}

I am unable to create new .txt file using StreamWriter Class

Here is my code...
string path = Path.Combine(Environment.GetEnvironmentVariable("USERPROFILE"), "Music", "stream.txt");
StreamWriter sw = new StreamWriter("stream.txt");
sw.WriteLine("i am stream");
sw.Close();
You almost had the solution there:
string path = Path.Combine(Environment.GetEnvironmentVariable("USERPROFILE"),"Music", "stream.txt");
StreamWriter sw = new StreamWriter(path);
sw.WriteLine("i am stream");
sw.Close();
You just had to use the path variable you created :)
After execution remember to look in the Music folder for the stream.txt file
Check This one:-
using System;
using System.IO;
class Test
{
public static void Main()
{
string path = #"c:\temp\MyTest.txt";
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Hello");
sw.WriteLine("And");
sw.WriteLine("Welcome");
}
}
// Open the file to read from.
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
}
Reference

cannot convert string to System.IO.Stream

In this C# Project, I have a JSON file in which I will be serializing data to. As I know, you create a StreamWriter and use that stream writer as a parameter. However, when I create the stream writer with the file path of the JSON file as the parameter, is gives me an error: Argument 1: Cannot Convert String to System.IO.Stream
Here is the file
using Newtonsoft.Json;
using ProjectObjects;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System;
namespace level2
{
public static class Data
{
static string selectedTeamName,selectedPlayerName;
static Team selectedTeam = new Team("unknown");
static Player selectedPlayer = new Player(" ");
static List<Team> AllTeams = new List<Team>();
public static void LoadFromCSV(string name, CSVType type)
{
string directory = Directory.GetCurrentDirectory();
var dirinfo = new DirectoryInfo(directory);
var MaindataFileDir = Path.Combine(dirinfo.FullName, "N/A");
var file = new FileInfo(MaindataFileDir);
if (type.Equals(CSVType.BJA))
{
}else if (type.Equals(CSVType.DefenseStats))
{
}else if (type.Equals(CSVType.HitStat))
{
}
}
public static void SerializeTeam(string filename)
{
string directory = Directory.GetCurrentDirectory();
var dirinfo = new DirectoryInfo(directory);
var MaindataFileDir = Path.Combine(dirinfo.FullName, "/Data/Datar.json");
var file = new FileInfo(MaindataFileDir);
string filepath = directory + "/Data/Datar.json";
if (file.Exists)
{
var serializer = new JsonSerializer();
using (var writer = new StreamWriter(MaindataFileDir))
using (var textwriter = new JsonTextWriter(writer))
{
//serializer.Serialize(textwriter, AllTeams);not finished
}
}
}
public static void DeserializeTeam()
{
string directory = Directory.GetCurrentDirectory();
var dirinfo = new DirectoryInfo(directory);
var MaindataFileDir = Path.Combine(dirinfo.FullName, "/Data/Datar.json");
var file = new FileInfo(MaindataFileDir);
if (file.Exists)
{
var serializer = new JsonSerializer();
using (var writer = new StreamReader(MaindataFileDir))
using (var textreader = new JsonTextReader(writer))
{
//serializer.Deserialize(textreader, AllTeams);not finished
}
}
}
}
}
The reason I'm having a hard time understanding what the issue is is that on MSDN there is an example extremely similar to what I'm doing.
From Here:
using System;
using System.IO;
using System.Text;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
string fileName = "test.txt";
string textToAdd = "Example text in file";
using (StreamWriter writer = new StreamWriter(fileName))
{
writer.Write(textToAdd);
}
}
}
}
In case it's important, I'm using Microsoft Visual Studio 2017 Community.
excuse my poor formatting.
Thank You in advance.

Read the content of an xml file within a zip package

I am required to read the contents of an .xml file using the Stream (Here the xml file is existing with in the zip package). Here in the below code, I need to get the file path at runtime (here I have hardcoded the path for reference). Please let me know how to read the file path at run time.
I have tried to use string s =entry.FullName.ToString(); but get the error "Could not find the Path". I have also tried to hard code the path as shown below. however get the same FileNotFound error.
string metaDataContents;
using (var zipStream = new FileStream(#"C:\OB10LinuxShare\TEST1\Temp" + "\\"+zipFileName+".zip", FileMode.Open))
using (var archive = new ZipArchive(zipStream, ZipArchiveMode.Read))
{
foreach (var entry in archive.Entries)
{
if (entry.Name.EndsWith(".xml"))
{
FileInfo metadataFileInfo = new FileInfo(entry.Name);
string metadataFileName = metadataFileInfo.Name.Replace(metadataFileInfo.Extension, String.Empty);
if (String.Compare(zipFileName, metadataFileName, true) == 0)
{
using (var stream = entry.Open())
using (var reader = new StreamReader(stream))
{
metaDataContents = reader.ReadToEnd();
clientProcessLogWriter.WriteToLog(LogWriter.LogLevel.DEBUG, "metaDataContents : " + metaDataContents);
}
}
}
}
}
I have also tried to get the contents of the .xml file using the Stream object as shown below. But here I get the error "Stream was not readable".
Stream metaDataStream = null;
string metaDataContent = string.Empty;
using (Stream stream = entry.Open())
{
metaDataStream = stream;
}
using (var reader = new StreamReader(metaDataStream))
{
metaDataContent = reader.ReadToEnd();
}
Kindly suggest, how to read the contents of the xml with in a zip file using Stream and StreamReader by specifying the file path at run time
Your section code snippet is failing because when you reach the end of the first using statement:
using (Stream stream = entry.Open())
{
metaDataStream = stream;
}
... the stream will be disposed. That's the point of a using statment. You should be fine with this sort of code, but load the XML file while the stream is open:
XDocument doc;
using (Stream stream = entry.Open())
{
doc = XDocument.Load(stream);
}
That's to load it as XML... if you really just want the text, you could use:
string text;
using (Stream stream = entry.Open())
{
using (StreamReader reader = new StreamReader(stream))
{
text = reader.ReadToEnd();
}
}
Again, note how this is reading before it hits the end of either using statement.
Here is a sample of how to read a zip file using .net 4.5
private void readZipFile(String filePath)
{
String fileContents = "";
try
{
if (System.IO.File.Exists(filePath))
{
System.IO.Compression.ZipArchive apcZipFile = System.IO.Compression.ZipFile.Open(filePath, System.IO.Compression.ZipArchiveMode.Read);
foreach (System.IO.Compression.ZipArchiveEntry entry in apcZipFile.Entries)
{
if (entry.Name.ToUpper().EndsWith(".XML"))
{
System.IO.Compression.ZipArchiveEntry zipEntry = apcZipFile.GetEntry(entry.Name);
using (System.IO.StreamReader sr = new System.IO.StreamReader(zipEntry.Open()))
{
//read the contents into a string
fileContents = sr.ReadToEnd();
}
}
}
}
}
catch (Exception)
{
throw;
}
}

Trying to merge two zip files into 1 using c# and Ionic.dll

Here is the code
ZipFile zipnew = ZipFile.Read(strPath);
if (!File.Exists(path))
{
using (ZipFile zip = new ZipFile())
{
zip.Save(path);
}
}
string tmpname = fpath + "\\abtemp";
ZipFile zipold = ZipFile.Read(path);
foreach (ZipEntry zenew in zipnew)
{
string flna = zenew.FileName.ToString();
string tfn = '#' + flna.Replace("\\", "/");
Stream fstream = File.Open(tmpname, FileMode.OpenOrCreate, FileAccess.Write);
zenew.Extract(fstream);
string l = fstream.Length.ToString();
fstream.Close();
using (StreamReader sr = new StreamReader(tmpname))
{
var zn = zipold.UpdateEntry(flna, sr.BaseStream);
sr.Close();
sr.Dispose();
fstream.Dispose();
}
}
zipnew.Dispose();
File.Delete(tmpname);
File.Delete(strPath);
The problem is: I get no error and there are no files merged into zipold from zipnew.
Zipold is a blank zip file
You're code isn't 100% clear to me, the variable tfn doesn't seem to be used and i'm not quite following with all the disposes / deletes. But on the bright side i did get your code working, the main problem was that you're not calling the save method of zipold.
string path = "d:\\zipold.zip";
ZipFile zipnew = ZipFile.Read("d:\\zipnew.zip");
if (!File.Exists(path))
{
using (ZipFile zip = new ZipFile())
{
zip.Save(path);
}
}
string tmpname = "d:" + "\\temp.dat";
ZipFile zipold = ZipFile.Read(path);
foreach (ZipEntry zenew in zipnew)
{
string flna = zenew.FileName.ToString();
//string tfn = '\\' + flna.Replace("\\", "/"); useless line
Stream fstream = File.Open(tmpname, FileMode.OpenOrCreate, FileAccess.Write);
zenew.Extract(fstream);
string l = fstream.Length.ToString();
fstream.Close();
using (StreamReader sr = new StreamReader(tmpname))
{
var zn = zipold.UpdateEntry(flna, sr.BaseStream);
zipold.Save();
sr.Close();
sr.Dispose();
fstream.Dispose();
}
}
zipnew.Dispose();
static void Main(string[] args)
{
try
{
using (ZipFile zip1 = new ZipFile())
{
zip1.AddFile(#"SCAN0002.PDF");
zip1.AddFile(#"SCAN0003.PDF");
zip1.Save("SCAN0002.ZIP");
}
using (ZipFile zip2 = new ZipFile())
{
zip2.AddFile(#"SCAN0004.PDF");
zip2.AddFile(#"SCAN0005.PDF");
zip2.AddFile(#"SCAN0006.PDF");
zip2.Save("SCAN0003.ZIP");
}
ZipFile z3 = new ZipFile().Read2(File.ReadAllBytes("SCAN0002.ZIP"));
ZipFile z4 = new ZipFile().Read2(File.ReadAllBytes("SCAN0003.ZIP"));
using (ZipFile zip3 = new ZipFile())
{
zip3.Marge(z3).Marge(z4);
zip3.Save("SCAN0004.ZIP");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
and extend class
public static class ZipFileExt
{
public static ZipFile Read2(this ZipFile item, byte[] data)
{
return ZipFile.Read(new MemoryStream(data));
}
public static ZipFile Marge(this ZipFile item, ZipFile file)
{
foreach (var entry in file)
item.AddEntry(entry.FileName, entry.Extract2Byte());
return item;
}
public static byte[] Extract2Byte(this ZipEntry entry)
{
using (var ms = new MemoryStream())
{
entry.Extract(ms);
return ms.ToArray();
}
}
}
\P/
http://www.youtube.com/watch?v=Y7dRBmMsevk&list=RD02xcFzsvnMmXY

Categories