FileStream CopyTo different extension - pdf

Is it possible to convert xlsx to Pdf like that?
FileStream sourceStream = new FileStream("C:\\Users\\Import.xlsx", FileMode.Open);
FileStream targetStream = new FileStream("C:\\Users\\Import.pdf", FileMode.CreateNew);
sourceStream.CopyTo(targetStream);

No, you are just copying the file to a new name. The actual content of the file will be exactly the same. No conversion is being performed.

Related

Save picture directly to stream? [duplicate]

I have a filename pointing to a text file, including its path, as a string. Now I'd like to load this .csv file into memory stream. How should I do that?
For example, I have this:
Dim filename as string="C:\Users\Desktop\abc.csv"
Dim stream As New MemoryStream(File.ReadAllBytes(filename))
You don't need to load a file into a MemoryStream.
You can simply call File.OpenRead to get a FileStream containing the file.
If you really want the file to be in a MemoryStream, you can call CopyTo to copy the FileStream to a MemoryStream.
I had an XML file being read from disk, using the old XmlReader API. How to read the XML file into memory, and then work with it in memory, instead of reading the disk repeatedly? Based on VB answer from Centro (upvoted) but with a Using block, and in C#.
The key line:
MemoryStream myXMLDocument = new MemoryStream(File.ReadAllBytes(#"c:\temp\myDemoXMLDocument.xml"));
Re the OP's question, if you wanted to load a CSV file into a MemoryStream:
MemoryStream myCSVDataInMemory = new MemoryStream(File.ReadAllBytes(#"C:\Users\Desktop\abc.csv"));
Following is a code snippet showing code to reads through XML document now that it's in a MemoryStream. Basically the same code as when it was coming from a FileStream that pointed to a file on disk. Yes, the XMLTextReader API is old and clunky, but it's what I had to work with in this app.
string myXMLFileName = #"c:\temp\myDemoXMLDocument.xml";
using (MemoryStream myXMLDocument = new MemoryStream(File.ReadAllBytes(myXMLFileName)))
{
myXMLTextReader = new XmlTextReader(myXMLDocument);
myXMLTextReader.WhitespaceHandling = WhitespaceHandling.None;
myXmlTextReader.Read(); // read the XML declaration node, advance to <Batch> tag
while (!myXmlTextReader.EOF)
{
if (myXmlTextReader.Name == "xml" && !myXmlTextReader.IsStartElement()) break;
// advance to <Batch> tag
while (myXmlTextReader.Name == "Batch" && myXmlTextReader.IsStartElement())
{
string BatchIdentifier = myXmlTextReader.GetAttribute("BatchIdentifier");
myXmlTextReader.Read(); // advance to next tag
while (!myXmlTextReader.EOF)
{
if (myXmlTextReader.Name == "Transaction" && myXmlTextReader.IsStartElement())
{
// Start a new set of items
string transactionID = myXmlTextReader.GetAttribute("ID");
myXmlTextReader.Read(); // Read next element, possibly another Transaction tag
}
}
//All Batch tags are completed.Move to next tag
myXmlTextReader.Read();
}
// Close the XML memory stream.
myXmlTextReader.Close();
myXmlDocument.Close();
}
}
You can copy it to a file stream like so:
string fullPath = Path.Combine(filePath, fileName);
FileStream fileStream = new FileStream(fullPath, FileMode.Open);
Image image = Image.FromStream(fileStream);
MemoryStream memoryStream = new MemoryStream();
image.Save(memoryStream, ImageFormat.Jpeg);
//Close File Stream
fileStream.Close();

how to use Aspose.word insert the mergefield and save into memeory steam

I have a project need to merge the text into merge fields in words 2010 using Aspose.words. I know to do the merge. After merge, I want to create it as filestream then save it to memeorystream then I will open it into the page and the user can choose save it or just open like that:
You can use the following overload of Save method to send the merged document to client browser.
doc.Save(Response, "Report Out.doc", ContentDisposition.Inline, null);
I work as developer evangelist at Aspose.
var stream = new MemoryStream();
document.Save(stream, SaveFormat.Docx);
var str = stream.ToArray();
MemoryStream ms = new MemoryStream(str);
FileStream file = new FileStream("your path", FileMode.Create, FileAccess.Write);
ms.WriteTo(file);
Here you go buddy, just close the file and memory stream. You will be having the stream, which you asked for.

Need a more efficent way to merge text files

This is my code at present
Dim Paths() As String = Directory.GetFiles("files*.txt")
For Each Path As String In Paths
File.AppendAllText("merged.txt", File.ReadAllText(Path), Encoding.Default)
Next
The problem seems that using this method, performance is poort when dealing with several large files.
Is there a more efficent way to merge text files? Maybe reading all the files into a streamreader first and then creating the output file in one operation?
try this:
using (StreamWriter sw = new StreamWriter("merge.txt"))
{
string[] paths = Directory.GetFiles("files*.txt");
foreach (string path in paths)
using (StreamReader sr = new StreamReader(path))
{
sw.Write(sr.ReadToEnd());
sw.WriteLine("");
}
}
I think that the slow operation is in File.AppendAllText that open->write->close the merge.txt file for each txt file in directory

Winrt StreamWriter & StorageFile does not completely Overwrite File

Quick search here yielded nothing. So, I have started using some rather roundabout ways to use StreamWriter in my WinRT Application. Reading works well, writing works differently. What' I'm seeing is that when I select my file to write, if I choose a new file then no problem. The file is created as I expect. If I choose to overwrite a file, then the file is overwritten to a point, but the point where the stream stops writing, if the original file was large, then the old contents exist past where my new stream writes.
The code is as such:
public async void WriteFile(StorageFile selectedFileToSave)
{
// At this point, selectedFileToSave is from the Save File picker so can be a enw or existing file
StreamWriter writeStream;
Encoding enc = new UTF8Encoding();
Stream dotNetStream;
dotNetStream = await selectedFileToSave.OpenStreamForWriteAsync();
StreamWriter writeStream = new StreamWriter(dotNetStream, enc);
// Do writing here
// Close
writeStream.Write(Environment.NewLine);
await writeStream.FlushAsync();
await dotNetStream.FlushAsync();
}
Can anyone offer clues on what I could be missing? There are lots of functions missing in WinRT, so not really following ways to get around this
Alternatively you can set length of the stream to 0 with SetLength method before using StreamWriter:
var stream = await file.OpenStreamForWriteAsync();
stream.SetLength(0);
using (var writer = new StreamWriter(stream))
{
writer.Write(text);
}
Why not just use the helper methods in FileIO class? You could call:
FileIO.WriteTextAsync(selectedFileToSave, newTextContents);
If you really need a StreamWriter, first truncate the file by calling
FileIO.WriteBytesAsync(selectedFileToSave, new byte[0]);
And then continue with your existing code.

How to fix exception MethodAccessException during file reading?

I have to read a text file which added in my project DataMid/Bigram_MidWord.txt where DataMid is a folder and Bigram_MidWord.txt is a file to read.
When i write the statement
FileStream fileStream = new FileStream(#"/SourceCode,component/DataMid/Bigram_MidWord.txt", FileMode.Open, FileAccess.ReadWrite);
then i get the exception as follows:
Attempt to access the method failed: System.IO.FileStream..ctor(System.String, System.IO.FileMode, System.IO.FileAccess)
How can I fix this issue?
The problem is that you are trying to use FileStream to access a resource that is embedded in your application's XAP file. FileStream is used for accessing the file system (e.g. isolated storage).
To access a text file that is a resource in your XAP file, you can use the following code:
string text;
Uri uri = new Uri("("/AssembyName;component/DataMid/Bigram_MidWord.txt", UriKind.RelativeOrAbsolute);
StreamResourceInfo sri = App.GetResourceStream(uri);
StreamReader sr = new StreamReader(sri.Stream);
text= sr.ReadToEnd();
sr.Close();