I am testing this EDI standard: X12 Parser (link), now example in link have as result.txt. The code that does this is:
using OopFactory.X12.Parsing;
using OopFactory.X12.Parsing.Model;
namespace MyX12.Edi835Parser
{
class Program
{
static void Main(string[] args)
{
Stream transformStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("MyX12.Edi835Parser.X12-835-To-CSV.xslt");
Stream inputStream = new FileStream(args[0], FileMode.Open, FileAccess.Read);
Stream outputFile = new FileStream(args[1], FileMode.Create, FileAccess.Write);
X12Parser parser = new X12Parser();
Interchange interchange = parser.Parse(inputStream);
string xml = interchange.Serialize();
var transform = new XslCompiledTransform();
transform.Load(XmlReader.Create(transformStream));
transform.Transform(XmlReader.Create(new StringReader(xml)), new XsltArgumentList(), outputFile);
}
}
}
As you can see, the code has: Stream outputFile = new FileStream(args1 ... where args1 is in project properties / Debug set as Sample-Output.txt, which is the name of file that would be created.
Now, I want to have the result instead as Sample-Output.txt, in my console, something like this:
Stream outputFile = Console.Write();
Really thanks for help.
Console.OpenStandardOutput() acquires the standard output stream.
Try replacing
Stream outputFile = new FileStream(args[1], FileMode.Create, FileAccess.Write);
with
Stream outputFile = Console.OpenStandardOutput();
Related
I have a JSON file created, and I am going to zip it using DotNetZip.
Using with StreamWriter to zip it is working, if I try to use MemoryStream it will not working.
StreamWriter :
sw = new StreamWriter(assetsFolder + #"manifest.json");
sw.Write(strManifest);
sw.Close();
zip.AddFile(Path.Combine(assetsFolder, "manifest.json"), "/");
zip.AddFile(Path.Combine(assetsFolder, "XXXXXXX"), "/");
zip.Save(outputStream);
MemoryStream :
var manifestStream = GenerateStreamFromString(strManifest);
public static Stream GenerateStreamFromString(string s)
{
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
zip.AddEntry("manifest.json", manifestStream);
zip.AddFile(Path.Combine(assetsFolder, "XXXXXXX"), "/");
zip.Save(outputStream);
I must using the .JSON file type to zip it, Can any one told me where have a mistake?
To create a Gzipped Json you need to use GZipStream. Try method below.
https://www.dotnetperls.com/gzipstream
GZipStream compresses data. It saves data efficiently—such as in
compressed log files. We develop a utility method in the C# language
that uses the System.IO.Compression namespace. It creates GZIP files.
It writes them to the disk.
public static void CompressStringToFile(string fileName, string value)
{
// A.
// Write string to temporary file.
string temp = Path.GetTempFileName();
File.WriteAllText(temp, value);
// B.
// Read file into byte array buffer.
byte[] b;
using (FileStream f = new FileStream(temp, FileMode.Open))
{
b = new byte[f.Length];
f.Read(b, 0, (int)f.Length);
}
// C.
// Use GZipStream to write compressed bytes to target file.
using (FileStream f2 = new FileStream(fileName, FileMode.Create))
using (GZipStream gz = new GZipStream(f2, CompressionMode.Compress, false))
{
gz.Write(b, 0, b.Length);
}
}
I have a C# app that tries to read a log file which is being written to by another app. When I try to read the file, I get IOException
"The process cannot access the file ... because it is being used by
another process."
What I tried using so far are the following, but none of them fix the problem
var log = File.ReadAllText(logPath);
var stream = new FileStream(logPath, FileMode.Open);
using (var stream = File.Open(logPath, FileMode.Open))
{
}
try this:
FileStream logFileStream = new FileStream("c:\test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
StreamReader logFileReader = new StreamReader(logFileStream);
while (!logFileReader.EndOfStream)
{
string line = logFileReader.ReadLine();
// Your code here
}
// Clean up
logFileReader.Close();
logFileStream.Close();
edited with MethodMan's suggestions
using(FileStream logFileStream = new FileStream(#"c:\test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using(StreamReader logFileReader = new StreamReader(logFileStream))
{
string text = logFileReader.ReadToEnd();
// Your code..
}
}
You can do nothing, if the "another app" does not use Share.Read while creating/opening the file.
I want to rewrite text file using StreamWriter. but when StreamWriter uses stream (like following code), the text will append to file.
StreamWriter sw = new StreamWriter(fstream);
sw.Write(text);
sw.Close();
i must use Stream in code because of that file share limitation
FileMode.Create ll create a new file. If the file excists, it ll show exception. Use FileMode.Truncate.
string txt="your text";
using (FileStream fs = new FileStream(#"C:\Users\rajesh.kumar\Desktop\test123.txt", FileMode.Truncate))
{
using (StreamWriter writer = new StreamWriter(fs))
{
writer.Write("txt");
}
}
If you use file stream, set FileMode:
using (FileStream fs = new FileStream(fileName, FileMode.CreateNew))
{
using (StreamWriter writer = new StreamWriter(fs))
{
writer.Write(textToAdd);
}
}
Person person = GetPerson();
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add(string.Empty, string.Empty);
XmlSerializer serializer = new XmlSerializer(typeof(Person));
string personText = string.Empty;
using (MemoryStream memoryStream = new MemoryStream())
{
using (XmlWriter xmlWriter = XmlWriter.Create(memoryStream, new XmlWriterSettings() { Encoding = Encoding.UTF8 }))
{
serializer.Serialize(xmlWriter, person, ns);
xmlWriter.Flush();
personText = Encoding.UTF8.GetString(memoryStream.ToArray());
}
}
string path = #"D:\person.xml";
// Write method 1:
File.WriteAllText(path, personText);
// Write method 2:
using (StreamWriter streamWriter = new StreamWriter(path, false , Encoding.UTF8))
{
streamWriter.Write(personText);
}
// Read the xml
using (FileStream fileStream = new FileStream(path, FileMode.Open))
{
return XDocument.Load(XmlReader.Create(fileStream));
}
When I read the xml after writing using method 2, I get this Data at the root level is invalid. Line 1, position 1. But it works fine using method 1.
What is causing this? Any pointers appreciated.
The problem is that both the StreamWriter and the XmlWriter are adding a byte-order-mark.
Options:
String the BOM from personText to start with
Pass new UTF8Encoding(false) instead of Encoding.UTF8 for the StreamWriter
Pass new UTF8Encoding(false) instead of Encoding.UTF8 for the XmlWriter
Avoid converting to text and back again in the first place: you've got the binary data in the MemoryStream, why not just dump that to disk?
Below is my Code I am generating Password Protected pdf from ItextSharp.
Actually two pdf are getting generating and saving.
But i want only file to be saved.
If I use same for input and output i am getting error.
Truly appreciate your help.
Letter1 mydoc = new Letter1();
mydoc.GenerateLetter();
string WorkingFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string InputFile = Path.Combine(WorkingFolder, "Testing1.pdf");
FileStream f = new FileStream(InputFile, FileMode.Create);
f.Write(mydoc.DocumentBytes, 0, mydoc.DocumentBytes.Length);
f.Close();
string OutputFile = Path.Combine(WorkingFolder, "TestingOut1.pdf");
using (Stream input = new FileStream(InputFile, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read))
{
using (Stream output = new FileStream(OutputFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
PdfReader reader = new PdfReader(input);
PdfEncryptor.Encrypt(reader, output, true, "abc123", "secret", PdfWriter.ALLOW_SCREENREADERS);
}
}
Consider using a MemoryStream
Untested code (written in browser:)
using (MemoryStream m = new MemoryStream())
{
m.Write(mydoc.DocumentBytes, 0, mydoc.DocumentBytes.Length);
m.Seek(0, SeekOrigin.Origin);
string OutputFile = Path.Combine(WorkingFolder, "TestingOut1.pdf");
using (Stream output = new FileStream(OutputFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
PdfReader reader = new PdfReader(m);
PdfEncryptor.Encrypt(reader, output, true, "abc123", "secret", PdfWriter.ALLOW_SCREENREADERS);
}
}
No need to instantiate a separate stream to read the PDF you want to encrypt. Use the PdfReader overloaded constructor that accepts a file path. Something like this:
PdfReader reader = new PdfReader(InputFile);
using (Stream output = new FileStream(
OutputFile, FileMode.Create, FileAccess.Write, FileShare.None
))
{
PdfEncryptor.Encrypt(
reader, output, true, "abc123", "secret", PdfWriter.ALLOW_SCREENREADERS
);
}