Copy and Paste files as a user - c#

In my application there are some files. Which I want to be able to copy and paste elsewhere in application.
The file I want to copy and paste I have stored inside a function GetPartialExportString()
My Idea:
When User clicks on "Copy" I create one file somewhere on comp and store it inside new created file
When user clicks "Paste" I Read from the file I generated when I clicked copy and add it there.
MemoryStream destinationStream = new MemoryStream();
protected void CopyCommand()
{
var modelAsString = GetPartialExportString();
string fileName = "copy.xaml";
string targetPath = #"C:\Users\";
string destFile = System.IO.Path.Combine(targetPath, fileName);
//System.IO.Directory.CreateDirectory(targetPath);
// convert string to stream
byte[] byteArray = Encoding.UTF8.GetBytes(modelAsString);
MemoryStream readingStream = new MemoryStream(byteArray);
FileStream file = new FileStream(fileName, FileMode.Create, FileAccess.Write);
readingStream.WriteTo(file);
file.Close();
readingStream.Close();
readingStream.CopyTo(destinationStream);
File.WriteAllText(destFile, modelAsString);
}
protected void PasteCommand()
{
string importString = File.ReadAllText("d:\\temp.txt");
LoadUnitFromXamlString("d:\\temp.txt");
}
It does not work like this. New to this, if someone can help I would appreciate!
File routes are incorect at the moment. But even when they were normal it was not working!

You should avoid overriding Close() method of Stream class for MemoryStream/FileStream objects. Use Dispose() instead.
You should get all the work done by the stream objects first and then dispose them.
After you've copied the contents of readingStream object to file, you'll have to readjust the position of stream buffer to the beginning of the contents present in readingStream object so as to copy it successfully to destinationStream.
Modify your code snippet like this:
readingStream.WriteTo(file);
readingStream.Position = 0;
readingStream.CopyTo(destinationStream);
file.Dispose();
readingStream.Dispose();
File.WriteAllText(destFile, modelAsString);

Related

Is possible to create zip password protected file without first creating file, then zip it

I am writing data into text file and using below code,
await using var file = new StreamWriter(filePath);
foreach (var packet in resultPackets)
{
file.WriteLine(JsonConvert.SerializeObject(packet));
}
And I am using below code to zip the file with password protected using `DotNetZip,
using (ZipFile zip = new ZipFile())
{
zip.Password = "password";
zip.AddFile(filePath);
zip.Save(#"C:\tmp\data4.zip");
}
Is there a way to combined both, I want to create a file on the fly as password protected.
I don't
want to create first file with data, t
then create zip file from it
and delete the base file
Is this possible? Thanks!
Okay, so since this is still unanswered, here's a small program that does the job for me:
using (var stream = new MemoryStream())
using (var streamWriter = new StreamWriter(stream))
{
// Insert your code in here, i.e.
//foreach (var packet in resultPackets)
//{
// streamWriter.WriteLine(JsonConvert.SerializeObject(packet));
//}
// ... instead I write a simple string.
streamWriter.Write("Hello World!");
// Make sure the contents from the StreamWriter are actually flushed into the stream, then seek the beginning of the stream.
streamWriter.Flush();
stream.Seek(0, SeekOrigin.Begin);
using (ZipFile zip = new ZipFile())
{
zip.Password = "password";
// Write the contents of the stream into a file that is called "test.txt"
zip.AddEntry("test.txt", stream);
// Save the archive.
zip.Save("test.zip");
}
}
Note how AddEntry does not create any form of temporary file. Instead, when the archive is saved, the contents of the stream are read and put into a compressed file within the archive. However, be aware that the whole content of the file are completely kept in memory before it the archive is written to the disk.

Writing a byte array as a file to a web location

private void CreateFile(byte[] outByteArray)
{
//Create a new file containing the returned PDF document
string filename = "C:\\myfile.pdf";
FileStream fs2 = new FileStream(filename, FileMode.OpenOrCreate);
BinaryWriter w = new BinaryWriter(fs2);
w.Write(outByteArray);
w.Close();
fs2.Close();
}
This is my current code.
I am writing to the server's drive. It is working fine.
But now I have to write the byte array to a web folder
I mean to some folder like http://tyyet.com/rsfgqs/destination/
and save it there in the name myfile.pdf.
How can I do that?
Can I use HttpWebRequest for that?

Using updateEntry() method with dotnetzip won't overwrite files correctly

I've been having a bit of a problem lately. I've been trying to extract one zip file into a memory stream and then from that stream, use the updateEntry() method to add it to the destination zip file.
The problem is, when the file in the stream is being put into the destination zip, it works if the file is not already in the zip. If there is a file with the same name, it does not overwrite correctly. It says on the dotnetzip docs that this method will overwrite files that are present in the zip with the same name but it does not seem to work. It will write correctly but when I go to check the zip, the files that are supposed to be overwritten have a compressed byte size of 0 meaning something went wrong.
I'm attaching my code below to show you what I'm doing:
ZipFile zipnew = new ZipFile(forgeFile);
ZipFile zipold = new ZipFile(zFile);
using(zipnew) {
foreach(ZipEntry zenew in zipnew) {
percent = (current / zipnew.Count) * 100;
string flna = zenew.FileName;
var fstream = new MemoryStream();
zenew.Extract(fstream);
fstream.Seek(0, SeekOrigin.Begin);
using(zipold) {
var zn = zipold.UpdateEntry(flna, fstream);
zipold.Save();
fstream.Dispose();
}
current++;
}
zipnew.Dispose();
}
Although it might be a bit slow, I found a solution by manually deleting and adding in the file. I'll leave the code here in case anyone else comes across this problem.
ZipFile zipnew = new ZipFile(forgeFile);
ZipFile zipold = new ZipFile(zFile);
using(zipnew) {
// Loop through each entry in the zip file
foreach(ZipEntry zenew in zipnew) {
string flna = zenew.FileName;
// Create a new memory stream for extracted files
var ms = new MemoryStream();
// Extract entry into the memory stream
zenew.Extract(ms);
ms.Seek(0, SeekOrigin.Begin); // Rewind the memory stream
using(zipold) {
// Remove existing entry first
try {
zipold.RemoveEntry(flna);
zipold.Save();
}
catch (System.Exception ex) {} // Ignore if there is nothing found
// Add in the new entry
var zn = zipold.AddEntry(flna, ms);
zipold.Save(); // Save the zip file with the newly added file
ms.Dispose(); // Dispose of the stream so resources are released
}
}
zipnew.Dispose(); // Close the zip file
}

Sharing violation during save as on Ubuntu Linux

I'm new to C# and I'm having a bit of an issue when saving to a new file. My program has two options for saving: save & save as.
I was getting a sharing violation error when saving, but I fixed that by closing the previous filestream. However, I still cant figure out why my save as code is giving me a sharing violation error.
Here's the code:
// get a file stream from the file chooser
FileStream file = File.OpenWrite(saveFc.Filename);
// check to see if the file is Ok
bool fileOk = file.CanWrite;
if (fileOk == true)
{
// get the filename
string filename = file.Name;
// store the filename for later use
UtilityClass.filename = filename;
// get the text from textview1
string text = textview1.Buffer.Text;
// get a StreamWriter
StreamWriter writer = File.CreateText(filename);
// write to the file
writer.Write(text);
// close/save the file
writer.Close();
file.Close();
}
}
// close the file c
If you could help me figure it out that would be much appreciated. Thanks!
You're opening the same file twice:
FileStream file = File.OpenWrite(saveFc.Filename);
And:
string filename = file.Name;
StreamWriter writer = File.CreateText(filename);
Your code could probably be simplified to:
using (var writer = File.CreateText(saveFc.Filename))
{
// store the filename for later use
UtilityClass.filename = saveFc.Filename;
// get the text from textview1
string text = textview1.Buffer.Text;
// write the text
writer.Write(text);
}
If you open the file with CreateText/OpenWrite it will always be writeable (or an exception will be thrown). The using block will automatically close the writer when it exits.

Create a temporary file from stream object in c#

Given a stream object which contains an xlsx file, I want to save it as a temporary file and delete it when not using the file anymore.
I thought of creating a class that implementing IDisposable and using it with the using code block in order to delete the temp file at the end.
Any idea of how to save the stream to a temp file and delete it on the end of use?
Thanks
You could use the TempFileCollection class:
using (var tempFiles = new TempFileCollection())
{
string file = tempFiles.AddExtension("xlsx");
// do something with the file here
}
What's nice about this is that even if an exception is thrown the temporary file is guaranteed to be removed thanks to the using block. By default this will generate the file into the temporary folder configured on the system but you could also specify a custom folder when invoking the TempFileCollection constructor.
You can get a temporary file name with Path.GetTempFileName(), create a FileStream to write to it and use Stream.CopyTo to copy all data from your input stream into the text file:
var stream = /* your stream */
var fileName = Path.GetTempFileName();
try
{
using (FileStream fs = File.OpenWrite(fileName))
{
stream.CopyTo(fs);
}
// Do whatever you want with the file here
}
finally
{
File.Delete(fileName);
}
Another approach here would be:
string fileName = "file.xslx";
int bufferSize = 4096;
var fileStream = System.IO.File.Create(fileName, bufferSize, System.IO.FileOptions.DeleteOnClose)
// now use that fileStream to save the xslx stream
This way the file will get removed after closing.
Edit:
If you don't need the stream to live too long (eg: only a single write operation or a single loop to write...), you can, as suggested, wrap this stream into a using block. With that you won't have to dispose it manually.
Code would be like:
string fileName = "file.xslx";
int bufferSize = 4096;
using(var fileStream = System.IO.File.Create(fileName, bufferSize, System.IO.FileOptions.DeleteOnClose))
{
// now use that fileStream to save the xslx stream
}
// Get a random temporary file name w/ path:
string tempFile = Path.GetTempFileName();
// Open a FileStream to write to the file:
using (Stream fileStream = File.OpenWrite(tempFile)) { ... }
// Delete the file when you're done:
File.Delete(tempFile);
EDIT:
Sorry, maybe it's just me, but I could have sworn that when you initially posted the question you didn't have all that detail about a class implementing IDisposable, etc... anyways, I'm not really sure what you're asking in your (edited?) question. But this question: Any idea of how to save the stream to temp file and delete it on the end of use? is pretty straight-forward. Any number of google results will come back for ".NET C# Stream to File" or such.
I just suggest for creating file use Path.GetTempFileName(). but others depends on your usage senario, for example if you want to create it in your temp creator class and use it just there, it's good to use using keyword.

Categories