Copy a file but with a "Save as" window - c#

I just want to copy a file to another location. But with a FileDialog.
I tried the code below but this is not working as I want...
Is there any other solution ?
SaveFileDialog saveFile = new SaveFileDialog();
if (saveFile.ShowDialog() == DialogResult.OK)
{
string newDirectory = saveFile.FileName;
System.IO.File.Copy(Path, newDirectory);
}
EDIT :
I want something like this :
Word exemple
A Filedialog with the default name of my source file and the right type. You can see an example when you try to save a Word.

Use the FileStream class . Which is more flexible, especially if you want to track the data transfer process byte by byte.
SaveFileDialog saveFile = new SaveFileDialog();
if (saveFile.ShowDialog() == DialogResult.OK)
{
string newDirectory = saveFile.FileName;
byte[] buffer = new byte[1024 * 1024];
int currentBlockSize = 0;
using (source = new FileStream(Path, FileMode.Open, FileAccess.Read))
{
using (dest = new FileStream(newDirectory, FileMode.CreateNew, FileAccess.Write))
{
while ((currentBlockSize = source.Read(buffer, 0, buffer.Length)) > 0)
{
dest.Write(buffer, 0, currentBlockSize);
}
}
}
}

Related

How to use filestream for copying files in c#

I want to copy a file from one folder to another folder using filestream.How this can be achived.when I try to use file.copy I was getting this file is using by another process, to avoid this I want to use file stream using c#. Can some one provide a sample for copying a file from one folder to another.
for copying i used below code :-
public static void Copy(string inputFilePath, string outputFilePath)
{
int bufferSize = 1024 * 1024;
using (FileStream fileStream = new FileStream(outputFilePath, FileMode.OpenOrCreate, FileAccess.Write,FileShare.ReadWrite))
//using (FileStream fs = File.Open(<file-path>, FileMode.Open, FileAccess.Read, FileShare.Read))
{
FileStream fs = new FileStream(inputFilePath, FileMode.Open, FileAccess.ReadWrite);
fileStream.SetLength(fs.Length);
int bytesRead = -1;
byte[] bytes = new byte[bufferSize];
while ((bytesRead = fs.Read(bytes, 0, bufferSize)) > 0)
{
fileStream.Write(bytes, 0, bytesRead);
}
}
}
You can use Stream.CopyTo method to copy the file like below:
public static string CopyFileStream(string outputDirectory, string inputFilePath)
{
FileInfo inputFile = new FileInfo(inputFilePath);
using (FileStream originalFileStream = inputFile.OpenRead())
{
var fileName = Path.GetFileName(inputFile.FullName);
var outputFileName = Path.Combine(outputDirectory, fileName);
using (FileStream outputFileStream = File.Create(outputFileName))
{
originalFileStream.CopyTo(outputFileStream);
}
return outputFileName;
}
}
string fileName = "Mytest.txt";
string sourcePath = #"C:\MyTestPath";
string targetPath = #"C:\MyTestTarget";
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
{
System.IO.Directory.CreateDirectory(targetPath);
}
// To copy a file to another location and
// overwrite the destination file if it already exists.
System.IO.File.Copy(sourceFile, destFile, true);

FileStream not working properly

I am trying to read/write files using ReadBytemethod. code is working but I have noticed that they are not available after process.I cant open them.I images not displaying.what am i doing wrong again and again.
if (openFileDialog1.ShowDialog() == DialogResult.OK) {
if (saveFileDialog1.ShowDialog() == DialogResult.OK) {
FileStream fsRead =
new FileStream(openFileDialog1.FileName, FileMode.Open);
FileStream fswrite =
new FileStream(saveFileDialog1.FileName, FileMode.Create);
if (fsRead.Position != fsRead.Length) {
byte b = (byte)fsRead.ReadByte();
fswrite.WriteByte(b);
}
}
}
You're only reading a single byte - I suspect you meant to write a while loop instead of an if statement:
while (fsRead.Position != fsRead.Length) {
byte b = (byte)fsRead.ReadByte();
fswrite.WriteByte(b);
}
However, that's still not very efficient. Typically it's better to read and write chunks at a time, using "I can't read any more" to indicate the end of the file:
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = fsRead.Read(buffer, 0, buffer.Length)) > 0) {
fswrite.Write(buffer, 0, bytesRead);
}
However, you don't really need to do this yourself, as you can use Stream.CopyTo to do it for you:
fsRead.CopyTo(fswrite);
Note that you should also use using statements for your streams, to close them automatically at the end of the statement. I'd also use File.OpenWrite and File.OpenRead rather than calling the FileStream constructor, and just use a Stream variable:
using (Stream read = File.OpenRead(openFileDialog1.FileName),
write = File.OpenWrite(saveFileDialog1.FileName))
{
read.CopyTo(write);
}
Or just use File.Copy of course!
You need to close files after using, they are locked until that.
Best practice is to use using (var fs = new FileStream(...) { ... } construct - in that case, file streams and underlying files will be closed after using scope is finished.
So it should be something like this:
if (openFileDialog1.ShowDialog() == DialogResult.OK) {
if (saveFileDialog1.ShowDialog() == DialogResult.OK) {
using (FileStream fsRead = new FileStream(openFileDialog1.FileName, FileMode.Open))
using (FileStream fswrite = new FileStream(saveFileDialog1.FileName, FileMode.Create)) {
// your logic here
if (fsRead.Position != fsRead.Length) {
byte b = (byte)fsRead.ReadByte();
fswrite.WriteByte(b);
}
}
}

after selecting image display same image inside picturebox

on buttonclick I'm taking image from file system and save into database, everything is ok but I want when I select image to display that image into pictureBox1
OpenFileDialog open = new OpenFileDialog() { Filter = "Image Files(*.jpeg;*.bmp;*.png;*.jpg)|*.jpeg;*.bmp;*.png;*.jpg" };
if (open.ShowDialog() == DialogResult.OK)
{
txtPhoto.Text = open.FileName;
}
string image = txtPhoto.Text;
Bitmap bmp = new Bitmap(image);
FileStream fs = new FileStream(image, FileMode.Open, FileAccess.Read);
byte[] bimage = new byte[fs.Length];
fs.Read(bimage, 0, Convert.ToInt32(fs.Length));
fs.Close();
byte[] Photo = bimage;
You can use Image property to set the Image for PictureBox Control.
Try This:
DialogResult result= openFileDialog1.ShowDialog();
if(result==DialogResult.OK)
pictureBox1.Image =new Bitmap(openFileDialog1.FileName);
if you want to add it in your code
Complete Code:
OpenFileDialog open = new OpenFileDialog() { Filter = "Image Files(*.jpeg;*.bmp;*.png;*.jpg)|*.jpeg;*.bmp;*.png;*.jpg" };
if (open.ShowDialog() == DialogResult.OK)
{
txtPhoto.Text = open.FileName;
}
string image = txtPhoto.Text;
Bitmap bmp = new Bitmap(image);
pictureBox1.Image = bmp;//add this line
FileStream fs = new FileStream(image, FileMode.Open, FileAccess.Read);
byte[] bimage = new byte[fs.Length];
fs.Read(bimage, 0, Convert.ToInt32(fs.Length));
fs.Close();
byte[] Photo = bimage;
Simple code:
picturebox.Image = Bitmap.FromFile(yourimagepath);
OpenFileDialog open = new OpenFileDialog()
{
Filter = "Image Files(*.jpeg;*.bmp;*.png;*.jpg)|*.jpeg;*.bmp;*.png;*.jpg"
};
if (open.ShowDialog() == DialogResult.OK)
{
PictureBoxObjectName.Image = Image.FromFile(open.FileName);
}
openFileDialog1.Multiselect = false;
openFileDialog1.Filter= "jpg files (*.jpg)|*.jpg";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
foreach (String file in openFileDialog1.FileNames)
{
picturebox1.Image = Image.FromFile(File);
}
}
This is for selection of one image.

If Filename place to dir dont work

I have problem with small thing...i coding auto updater and when i downloading .exe file i want to place it to main dir..and others .extension to sub dir.
File.exe = Here is i download place to main dir
Else = place to sub dir...but it isnt working, place all to main dir
if(ex[1] == "File.exe")
{
if (File.Exists(path))
{
if(File.Exists(String.Format("{0}WoW.exe", wow.GetValue("InstallPath").ToString())))
{
File.Copy(String.Format("{0}WoW.exe", wow.GetValue("InstallPath").ToString()), String.Format("{0}WoW_zaloha_Awrodar_old_file.exe", wow.GetValue("InstallPath").ToString()), false);
File.Delete(String.Format("{0}WoW.exe", wow.GetValue("InstallPath").ToString()));
}
else if(File.Exists(String.Format("{0}Wow.exe", wow.GetValue("InstallPath").ToString())))
{
File.Copy(String.Format("{0}Wow.exe", wow.GetValue("InstallPath").ToString()), String.Format("{0}Wow_zaloha_Awrodar_old_file.exe", wow.GetValue("InstallPath").ToString()), false);
File.Delete(String.Format("{0}Wow.exe", wow.GetValue("InstallPath").ToString()));
}
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
MD5 md5 = new MD5CryptoServiceProvider();
byte[] retVal = md5.ComputeHash(fs);
fs.Close();
StringBuilder sb = new StringBuilder();
foreach(byte b in retVal)
sb.Append(string.Format("{0:X2}", b));
if(ex[2] == sb.ToString())
proceed = false;
}
}
else
{
if(File.Exists(MPQpath))
{
FileStream fs = new FileStream(MPQpath, FileMode.Open, FileAccess.Read, FileShare.Read);
MD5 md5 = new MD5CryptoServiceProvider();
byte[] retVal = md5.ComputeHash(fs);
fs.Close();
StringBuilder sb = new StringBuilder();
foreach(byte b in retVal)
sb.Append(string.Format("{0:X2}", b));
if(ex[2] == sb.ToString())
proceed = false;
}
}
Use Path.Combine for path manipulation to ensure correctness of filenames. Other than that I don't know what is wrong with your code. Have you traced it though to find out which line is causing your problem.

ICSharpCode.SharpZipLib.Zip.FastZip not zipping files having special characters in their file names

I am using ICSharpCode.SharpZipLib.Zip.FastZip to zip files but I'm stuck on a problem:
When I try to zip a file with special characters in its file name, it does not work. It works when there are no special characters in the file name.
I think you cannot use FastZip. You need to iterate the files and add the entries yourself specifying:
entry.IsUnicodeText = true;
To tell SharpZipLib the entry is unicode.
string[] filenames = Directory.GetFiles(sTargetFolderPath);
// Zip up the files - From SharpZipLib Demo Code
using (ZipOutputStream s = new
ZipOutputStream(File.Create("MyZipFile.zip")))
{
s.SetLevel(9); // 0-9, 9 being the highest compression
byte[] buffer = new byte[4096];
foreach (string file in filenames)
{
ZipEntry entry = new ZipEntry(Path.GetFileName(file));
entry.DateTime = DateTime.Now;
entry.IsUnicodeText = true;
s.PutNextEntry(entry);
using (FileStream fs = File.OpenRead(file))
{
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, 0, buffer.Length);
s.Write(buffer, 0, sourceBytes);
} while (sourceBytes > 0);
}
}
s.Finish();
s.Close();
}
You can continue using FastZip if you would like, but you need to give it a ZipEntryFactory that creates ZipEntrys with IsUnicodeText = true.
var zfe = new ZipEntryFactory { IsUnicodeText = true };
var fz = new FastZip { EntryFactory = zfe };
fz.CreateZip("out.zip", "C:\in", true, null);
You have to download and compile the latest version of SharpZipLib library so you can use
entry.IsUnicodeText = true;
here is your snippet (slightly modified):
FileInfo file = new FileInfo("input.ext");
using(var sw = new FileStream("output.zip", FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
using(var zipStream = new ZipOutputStream(sw))
{
var entry = new ZipEntry(file.Name);
entry.IsUnicodeText = true;
zipStream.PutNextEntry(entry);
using (var reader = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = reader.Read(buffer, 0, buffer.Length)) > 0)
{
byte[] actual = new byte[bytesRead];
Buffer.BlockCopy(buffer, 0, actual, 0, bytesRead);
zipStream.Write(actual, 0, actual.Length);
}
}
}
}
Possibility 1: you are passing a filename to the regex file filter.
Possibility 2: those characters are not allowed in zip files (or at least SharpZipLib thinks so)
try to take out the special character from the file name, i,e replace it.
your Filename.Replace("&", "&");

Categories