cannot convert string to System.IO.Stream - c#

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.

Related

Reading from XML file in memory using XmlSerializer

I use code below to open zip archive in memory.
using (var leagueFile = File.OpenRead(openFileDialog.FileName))
using (var package = new ZipArchive(leagueFile, ZipArchiveMode.Read))
{
foreach (var team in package.Entries)
{
if (team.Name.EndsWith(".xml"))
{
_xmlHandler.Import<Player>(team.FullName, Encoding.UTF8);
//...
}
}
}
When I try to deserialize with my Import<T>() method, app crashes due to file wasn't found.
public T Import<T>(string fileName, Encoding encoding) where T : class, new()
{
var serializer = new XmlSerializer(typeof(T));
serializer.UnknownNode += serializer_UnknownNode;
serializer.UnknownAttribute += serializer_UnknownAttribute;
var reader = XmlReader.Create(new StreamReader(fileName, encoding));
var po = (T)serializer.Deserialize(reader);
return po;
}
The problem is that app is searching for fileName in the bin directory of application. Not in stream (?) of zip archive. Is there a way to do this with XmlSerializer class?
Modify your code as below:
using (var leagueFile = File.OpenRead(openFileDialog.FileName))
using (var package = new ZipArchive(leagueFile, ZipArchiveMode.Read))
{
foreach (var team in package.Entries)
{
if (team.Name.EndsWith(".xml"))
{
using(var xmlStream = team.Open())
{
_xmlHandler.Import<Player>(xmlStream, Encoding.UTF8);
//...
}
}
}
}
public T Import<T>(Stream input, Encoding encoding) where T : class, new()
{
var serializer = new XmlSerializer(typeof(T));
serializer.UnknownNode += serializer_UnknownNode;
serializer.UnknownAttribute += serializer_UnknownAttribute;
var reader = XmlReader.Create(input);
var po = (T)serializer.Deserialize(reader);
return po;
}

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

How can I return a collection of large files without putting them in memory?

I need to write an API that retrieves a collection of file streams and then returns the files. These files can get large (~1GB). I need this to be as quick as possible, but this service can't consume too much memory.
In the past when I've had to do something like this, the files weren't large, so I just created a ZIP in memory and returned that. I'm not able to do that this time due to the memory constraint. From what I can tell, multipart responses don't exist, so I can't do that either. What options do I have? Is there some way I can stream zip back as a response?
public async Task GetFiles(string someId)
{
List<Stream> streamList = GetStreams(someId);
using (ZipArchive archive = new ZipArchive(responseStream /* ?? */, ZipArchiveMode.Create, true))
{
...
}
}
You could try using a gzipsteam, which avoids loading the files in memory.
https://msdn.microsoft.com/en-us/library/system.io.compression.gzipstream(v=vs.110).aspx
Here is the example from the page:
using System;
using System.IO;
using System.IO.Compression;
namespace zip
{
public class Program
{
private static string directoryPath = #"c:\temp";
public static void Main()
{
DirectoryInfo directorySelected = new DirectoryInfo(directoryPath);
Compress(directorySelected);
foreach (FileInfo fileToDecompress in directorySelected.GetFiles("*.gz"))
{
Decompress(fileToDecompress);
}
}
public static void Compress(DirectoryInfo directorySelected)
{
foreach (FileInfo fileToCompress in directorySelected.GetFiles())
{
using (FileStream originalFileStream = fileToCompress.OpenRead())
{
if ((File.GetAttributes(fileToCompress.FullName) &
FileAttributes.Hidden) != FileAttributes.Hidden & fileToCompress.Extension != ".gz")
{
using (FileStream compressedFileStream = File.Create(fileToCompress.FullName + ".gz"))
{
using (GZipStream compressionStream = new GZipStream(compressedFileStream,
CompressionMode.Compress))
{
originalFileStream.CopyTo(compressionStream);
}
}
FileInfo info = new FileInfo(directoryPath + "\\" + fileToCompress.Name + ".gz");
Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
fileToCompress.Name, fileToCompress.Length.ToString(), info.Length.ToString());
}
}
}
}
public static void Decompress(FileInfo fileToDecompress)
{
using (FileStream originalFileStream = fileToDecompress.OpenRead())
{
string currentFileName = fileToDecompress.FullName;
string newFileName = currentFileName.Remove(currentFileName.Length - fileToDecompress.Extension.Length);
using (FileStream decompressedFileStream = File.Create(newFileName))
{
using (GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress))
{
decompressionStream.CopyTo(decompressedFileStream);
Console.WriteLine("Decompressed: {0}", fileToDecompress.Name);
}
}
}
}
}
}

How can I create named destinations with iTextSharp?

I am trying to convert PDF bookmarks into named destinations with C# and iTextSharp 5 library. Unfortunately iTextSharp seems not to write named destinations into the target PDF file.
using System;
using System.Collections.Generic;
using iTextSharp.text.pdf;
using iTextSharp.text;
using System.IO;
namespace PDFConvert
{
class Program
{
static void Main(string[] args)
{
String InputPdf = #"test.pdf";
String OutputPdf = "out.pdf";
PdfReader reader = new PdfReader(InputPdf);
var fileStream = new FileStream(OutputPdf, FileMode.Create, FileAccess.Write, FileShare.None);
var list = SimpleBookmark.GetBookmark(reader);
PdfStamper stamper = new PdfStamper(reader, fileStream);
foreach (Dictionary<string, object> entry in list)
{
object o;
entry.TryGetValue("Title", out o);
String title = o.ToString();
entry.TryGetValue("Page", out o);
String location = o.ToString();
String[] aLoc = location.Split(' ');
int page = int.Parse(aLoc[0]);
PdfDestination dest = new PdfDestination(PdfDestination.XYZ, float.Parse(aLoc[2]), float.Parse(aLoc[3]), float.Parse(aLoc[4]));
stamper.Writer.AddNamedDestination(title, page, dest);
// stamper.Writer.AddNamedDestinations(SimpleNamedDestination.GetNamedDestination(reader, false), reader.NumberOfPages);
}
stamper.Close();
reader.Close();
}
}
}
I already tried to use PdfWriter instead of PdfStamper, with the same result. I have definitely calls of stamper.Writer.AddNamedDestination(title, page, dest); but no sign of NamedDestinations in my target file.
I have found a solution using iText 7 instead of 5. Unfortunately the syntax is completely different. In my code below I only consider the second level Bookmarks ("Outline") of my PDF.
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Navigation;
using System;
namespace PDFConvert
{
class Program
{
static void Main(string[] args)
{
String InputPdf = #"test.pdf";
String OutputPdf = "out.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfReader(InputPdf), new PdfWriter(OutputPdf));
PdfOutline outlines = pdfDoc.GetOutlines(false);
// first level
foreach (var outline in outlines.GetAllChildren())
{
// second level
foreach (var second in outline.GetAllChildren())
{
String title = second.GetTitle();
PdfDestination dest = second.GetDestination();
pdfDoc.AddNamedDestination(title, dest.GetPdfObject());
}
}
pdfDoc.Close();
}
}
}

How to write into an existing textfile in windows phone?

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);
}
}
}

Categories