How to rename an image - c#

I have an image, person1.png, and four other images, person2.png, person3.png, person5.png, and person4.png. I want to rename these images in C# code. How would I do this?

Since the PNG files are in your XAP, you can save them into your IsolatedStorage like this:
//make sure PNG_IMAGE is set as 'Content' build type
var pngStream= Application.GetResourceStream(new Uri(PNG_IMAGE, UriKind.Relative)).Stream;
int counter;
byte[] buffer = new byte[1024];
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(IMAGE_NAME, FileMode.Create, isf))
{
counter = 0;
while (0 < (counter = pngStream.Read(buffer, 0, buffer.Length)))
{
isfs.Write(buffer, 0, counter);
}
pngStream.Close();
}
}
Here you can save it to whatever file name you want by changing IMAGE_NAME.
To read it out again, you can do this:
byte[] streamData;
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isfs = isf.OpenFile("image.png", FileMode.Open, FileAccess.Read))
{
streamData = new byte[isfs.Length];
isfs.Read(streamData, 0, streamData.Length);
}
}
MemoryStream ms = new MemoryStream(streamData);
BitmapImage bmpImage= new BitmapImage();
bmpImage.SetSource(ms);
image1.Source = bmpImage; //image1 being your Image control

Use the FileInfo.MoveTo method documented here. Moving a file to the same path but with a different name is how you rename files.
FileInfo fInfo = new FileInfo ("path\to\person1.png");
fInfo.MoveTo("path\to\newname.png")
If you need to manipulate paths, use the Path.Combine method documented here

On Windows Phone 7 the API methods to copy or move (rename) a file don't exist. (See http://msdn.microsoft.com/en-us/library/57z06scs(v=VS.95).aspx) You therefore have to do this yourself.
Something like:
var oldName = "file.old"; var newName = "file.new";
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var readStream = new IsolatedStorageFileStream(oldName, FileMode.Open, store))
using (var writeStream = new IsolatedStorageFileStream(newName, FileMode.Create, store))
using (var reader = new StreamReader(readStream))
using (var writer = new StreamWriter(writeStream))
{
writer.Write(reader.ReadToEnd());
}
store.DeleteFile(oldName);
}

When you upload image this function auto change the image name to Full date and return the full path where the image saved and with it new name.
string path = upload_Image(FileUpload1, "~/images/");
if (!path.Equals(""))
{
//use the path var..
}
and this is the function
string upload_Image(FileUpload fileupload, string ImageSavedPath)
{
FileUpload fu = fileupload;
string imagepath = "";
if (fileupload.HasFile)
{
string filepath = Server.MapPath(ImageSavedPath);
String fileExtension = System.IO.Path.GetExtension(fu.FileName).ToLower();
String[] allowedExtensions = { ".gif", ".png", ".jpeg", ".jpg" };
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])
{
try
{
string s_newfilename = DateTime.Now.Year.ToString() +
DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() +
DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + fileExtension;
fu.PostedFile.SaveAs(filepath + s_newfilename);
imagepath = ImageSavedPath + s_newfilename;
}
catch (Exception ex)
{
return "";
}
}
}
}
return imagepath;
}
if you need more help i'll try :)

Related

Invalid zip file reading from a Stream in C#

I have the following code:
private static byte[] ConverterStringToByte(Stream body)
{
string fileName = "data_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".zip";
// Take out the bytes from the memory stream and safely close the stream
using (var ms = new MemoryStream())
{
body.CopyTo(ms);
using (var zipArchive = new ZipArchive(ms, ZipArchiveMode.Create, false))
{
var zipEntry = zipArchive.CreateEntry(fileName, CompressionLevel.Optimal);
using (BinaryWriter writer = new BinaryWriter(zipEntry.Open()))
{
ms.Position = 0;
writer.Write(ms.ToArray());
}
}
return ms.ToArray();
}
}
I am downloading the file successfully, however I'm getting
invalid file
when trying to open
I think it should be something like this. Not sure about fileName though, because it's the name of the file being put into archive, so I don't think it should have *.zip extension. Unless you are creating a zip of zips.
static byte[] ConverterStringToByte(Stream body)
{
string fileName = #"data_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".zip";
using (var ms = new MemoryStream())
{
using (var zipArchive = new ZipArchive(ms, ZipArchiveMode.Create, false))
{
var zipEntry = zipArchive.CreateEntry(fileName, CompressionLevel.Optimal);
using (var destStream = zipEntry.Open())
{
body.CopyTo(destStream);
}
}
return ms.ToArray();
}
}

Copy files from one Zip file to another

I am copying files from one zip file to another in certain circumstances. I am wondering if there is a better way to do it than what I came up with:
using FileStream sourceFileStream = new FileStream(source.FileName, FileMode.Open);
using FileStream targetFileStream = new FileStream(target.FileName, FileMode.Open, FileAccess.ReadWrite);
using ZipArchive sourceZip = new ZipArchive(sourceFileStream, ZipArchiveMode.Read);
using ZipArchive targetZip = new ZipArchive(targetFileStream, ZipArchiveMode.Update);
ZipArchiveEntry sourceEntry = sourceZip.GetEntry(filePathInArchive);
if (sourceEntry == null)
return;
ZipArchiveEntry targetEntry = targetZip.GetEntry(filePathInArchive);
if (targetEntry != null)
targetEntry.Delete();
targetZip.CreateEntry(filePathInArchive);
targetEntry = targetZip.GetEntry(filePathInArchive);
if (targetEntry != null)
{
Stream writer = targetEntry.Open();
Stream reader = sourceEntry.Open();
int b;
do
{
b = reader.ReadByte();
writer.WriteByte((byte)b);
} while (b != -1);
writer.Close();
reader.Close();
}
Tips and suggestions would be appreciated.
You can iterate each entry from source archive with opening its streams and using Stream.CopyTo write source entry content to target entry.
From C# 8.0 it looks compact and works fine:
static void CopyZipEntries(string sourceZipFile, string targetZipFile)
{
using FileStream sourceFS = new FileStream(sourceZipFile, FileMode.Open);
using FileStream targetFS = new FileStream(targetZipFile, FileMode.Open);
using ZipArchive sourceZIP = new ZipArchive(sourceFS, ZipArchiveMode.Read, false, Encoding.GetEncoding(1251));
using ZipArchive targetZIP = new ZipArchive(targetFS, ZipArchiveMode.Update, false, Encoding.GetEncoding(1251));
foreach (ZipArchiveEntry sourceEntry in sourceZIP.Entries)
{
// 'is' is replacement for 'null' check
if (targetZIP.GetEntry(sourceEntry.FullName) is ZipArchiveEntry existingTargetEntry)
existingTargetEntry.Delete();
using (Stream targetEntryStream = targetZIP.CreateEntry(sourceEntry.FullName).Open())
{
sourceEntry.Open().CopyTo(targetEntryStream);
}
}
}
With earlier than C# 8.0 versions it works fine too, but more braces needed:
static void CopyZipEntries(string sourceZipFile, string targetZipFile)
{
using (FileStream sourceFS = new FileStream(sourceZipFile, FileMode.Open))
{
using (FileStream targetFS = new FileStream(targetZipFile, FileMode.Open))
{
using (ZipArchive sourceZIP = new ZipArchive(sourceFS, ZipArchiveMode.Read, false, Encoding.GetEncoding(1251)))
{
using (ZipArchive targetZIP = new ZipArchive(targetFS, ZipArchiveMode.Update, false, Encoding.GetEncoding(1251)))
{
foreach (ZipArchiveEntry sourceEntry in sourceZIP.Entries)
{
if (targetZIP.GetEntry(sourceEntry.FullName) is ZipArchiveEntry existingTargetEntry)
{
existingTargetEntry.Delete();
}
using (Stream target = targetZIP.CreateEntry(sourceEntry.FullName).Open())
{
sourceEntry.Open().CopyTo(target);
}
}
}
}
}
}
}
For single specified file copy just replace bottom part from foreach loop to if condition:
static void CopyZipEntry(string fileName, string sourceZipFile, string targetZipFile)
{
// ...
// It means specified file exists in source ZIP-archive
// and we can copy it to target ZIP-archive
if (sourceZIP.GetEntry(fileName) is ZipArchiveEntry sourceEntry)
{
if (targetZIP.GetEntry(sourceEntry.FullName) is ZipArchiveEntry existingTargetEntry)
existingTargetEntry.Delete();
using (Stream targetEntryStream = targetZIP.CreateEntry(sourceEntry.FullName).Open())
{
sourceEntry.Open().CopyTo(targetEntryStream);
}
}
else
MessageBox.Show("Source ZIP-archive doesn't contains file " + fileName);
}
Thanks to the input so far, I cleaned up and improved the code. I think this looks cleaner and more reliable.
//Making sure files exist etc before this part...
string filePathInArchive = source.GetFilePath(fileId);
using FileStream sourceFileStream = new FileStream(source.FileName, FileMode.Open);
using FileStream targetFileStream = new FileStream(target.FileName, FileMode.Open, FileAccess.ReadWrite);
using ZipArchive sourceZip = new ZipArchive(sourceFileStream, ZipArchiveMode.Read, false );
using ZipArchive targetZip = new ZipArchive(targetFileStream, ZipArchiveMode.Update, false);
ZipArchiveEntry sourceEntry = sourceZip.GetEntry(filePathInArchive);
if (sourceEntry != null)
{
if (targetZip.GetEntry(filePathInArchive) is { } existingTargetEntry)
{
existingTargetEntry.Delete();
}
using var targetEntryStream = targetZip.CreateEntry(sourceEntry.FullName).Open();
sourceEntry.Open().CopyTo(targetEntryStream);
}

Read image file in Image object from zip file

I'm using iconic.dll file to read data from compressed files (.zip file extensions)
Please check my code below
string zippath = txtFilePath.Text.Trim() + "\\" + foldername + ".zip";
ArrayList arrFiles = new ArrayList();
using (ZipFile zip = ZipFile.Read(enrollment))
{
foreach (ZipEntry e1 in zip)
{
arrFiles.Add(e1.ToString());
}
}
foreach (string path in arrFiles)
{
Image img1 = Image.FromFile(path); //geting error on this line
imageList.Images.Add(getThumbnaiImage(imageList.ImageSize.Width, img1));
}
How can I read image files from a compressed folder?
Try this :
using (ZipFile zip = ZipFile.Read(enrollment))
{
ZipEntry entry = zip["Image.bmp"];
entry.Extract(outputStream);
}
Also you can show your image in a pricturebox :
PictureBox pb = new PictureBox();
pb.Location = new Point(100, 100);
pb.SizeMode = PictureBoxSizeMode.Zoom;
var bmp = new Bitmap(outputStream);
pb.Image = bmp;
this.Controls.Add(pb);
This seems to be the solution:
using (ZipFile zip = ZipFile.Read(enrollment))
{
foreach (ZipEntry e1 in zip)
{
CrcCalculatorStream reader = e1.OpenReader();
MemoryStream memstream = new MemoryStream();
reader.CopyTo(memstream);
byte[] bytes = memstream.ToArray();
Image img1 = Image.FromStream(memstream);
imageList.Images.Add(getThumbnaiImage(imageList.ImageSize.Width, img1));
}
}

Trying to merge two zip files into 1 using c# and Ionic.dll

Here is the code
ZipFile zipnew = ZipFile.Read(strPath);
if (!File.Exists(path))
{
using (ZipFile zip = new ZipFile())
{
zip.Save(path);
}
}
string tmpname = fpath + "\\abtemp";
ZipFile zipold = ZipFile.Read(path);
foreach (ZipEntry zenew in zipnew)
{
string flna = zenew.FileName.ToString();
string tfn = '#' + flna.Replace("\\", "/");
Stream fstream = File.Open(tmpname, FileMode.OpenOrCreate, FileAccess.Write);
zenew.Extract(fstream);
string l = fstream.Length.ToString();
fstream.Close();
using (StreamReader sr = new StreamReader(tmpname))
{
var zn = zipold.UpdateEntry(flna, sr.BaseStream);
sr.Close();
sr.Dispose();
fstream.Dispose();
}
}
zipnew.Dispose();
File.Delete(tmpname);
File.Delete(strPath);
The problem is: I get no error and there are no files merged into zipold from zipnew.
Zipold is a blank zip file
You're code isn't 100% clear to me, the variable tfn doesn't seem to be used and i'm not quite following with all the disposes / deletes. But on the bright side i did get your code working, the main problem was that you're not calling the save method of zipold.
string path = "d:\\zipold.zip";
ZipFile zipnew = ZipFile.Read("d:\\zipnew.zip");
if (!File.Exists(path))
{
using (ZipFile zip = new ZipFile())
{
zip.Save(path);
}
}
string tmpname = "d:" + "\\temp.dat";
ZipFile zipold = ZipFile.Read(path);
foreach (ZipEntry zenew in zipnew)
{
string flna = zenew.FileName.ToString();
//string tfn = '\\' + flna.Replace("\\", "/"); useless line
Stream fstream = File.Open(tmpname, FileMode.OpenOrCreate, FileAccess.Write);
zenew.Extract(fstream);
string l = fstream.Length.ToString();
fstream.Close();
using (StreamReader sr = new StreamReader(tmpname))
{
var zn = zipold.UpdateEntry(flna, sr.BaseStream);
zipold.Save();
sr.Close();
sr.Dispose();
fstream.Dispose();
}
}
zipnew.Dispose();
static void Main(string[] args)
{
try
{
using (ZipFile zip1 = new ZipFile())
{
zip1.AddFile(#"SCAN0002.PDF");
zip1.AddFile(#"SCAN0003.PDF");
zip1.Save("SCAN0002.ZIP");
}
using (ZipFile zip2 = new ZipFile())
{
zip2.AddFile(#"SCAN0004.PDF");
zip2.AddFile(#"SCAN0005.PDF");
zip2.AddFile(#"SCAN0006.PDF");
zip2.Save("SCAN0003.ZIP");
}
ZipFile z3 = new ZipFile().Read2(File.ReadAllBytes("SCAN0002.ZIP"));
ZipFile z4 = new ZipFile().Read2(File.ReadAllBytes("SCAN0003.ZIP"));
using (ZipFile zip3 = new ZipFile())
{
zip3.Marge(z3).Marge(z4);
zip3.Save("SCAN0004.ZIP");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
and extend class
public static class ZipFileExt
{
public static ZipFile Read2(this ZipFile item, byte[] data)
{
return ZipFile.Read(new MemoryStream(data));
}
public static ZipFile Marge(this ZipFile item, ZipFile file)
{
foreach (var entry in file)
item.AddEntry(entry.FileName, entry.Extract2Byte());
return item;
}
public static byte[] Extract2Byte(this ZipEntry entry)
{
using (var ms = new MemoryStream())
{
entry.Extract(ms);
return ms.ToArray();
}
}
}
\P/
http://www.youtube.com/watch?v=Y7dRBmMsevk&list=RD02xcFzsvnMmXY

Is there a library or tool for zipping numerous files

I've downloaded ICSharpCode.SharpZipLib and DotNetZip. I'm zipping over 100 files at a time varying a meg to 4 megs. When I use ICSharpCode I get a 'ContextSwitchDeadlock' error. DotNetZip fails on the finalizing of the file every time.
Also, I'm working on sharepoint folders (mapped to my local drive)
private bool zipall()
//ICSharpCode
{
int i = 0;
progressBarzipping.Minimum = 0;
progressBarzipping.Maximum = listBoxfiles.Items.Count;
ZipOutputStream zipOut = new ZipOutputStream(File.Create(textBoxDropPath.Text + "\\" + textBoxZipFileName.Text + ".zip"));
foreach (string fName in listBoxfiles.Items)
{
try
{
FileInfo fi = new FileInfo(fName);
ZipEntry entry = new ZipEntry(fi.Name);
FileStream sReader = File.OpenRead(fName);
byte[] buff = new byte[Convert.ToInt32(sReader.Length)];
sReader.Read(buff, 0, (int)sReader.Length);
entry.DateTime = fi.LastWriteTime;
entry.Size = sReader.Length;
sReader.Close();
zipOut.PutNextEntry(entry);
zipOut.Write(buff, 0, buff.Length);
}
catch
{
MessageBox.Show("Zip Failed");
zipOut.Finish();
zipOut.Close();
progressBarzipping.Value = 0;
return false;
}
i++;
progressBarzipping.Value = i;
}
zipOut.Finish();
zipOut.Close();
MessageBox.Show("Zip Complete");
progressBarzipping.Value = 0;
return true;
}
//Not sure but I think this was my DotNetZip approach
//using (ZipFile zip = new ZipFile())
// {
// foreach(string file in listboxFiles.Items)
// {
// zip.AddFile(file);
// }
// zip.Save(PathToNewZip);
// }
You didn't provide the exception. When using DotNetZip, I guess the problem might be with the sharepoint mapped drive. DotNetZip normally will save the zip as a temp file, then rename it. Maybe this isn't working because of sharepoint. If that's the case, try opening a filestream and saving it to that stream. This avoids the rename operation.
progressBarzipping.Minimum = 0;
progressBarzipping.Maximum = listBoxfiles.Items.Count;
using (Stream fs = new FileStream(PathToNewZip, FileMode.Create, FileAccess.Write))
{
using (ZipFile zip = new ZipFile())
{
zip.AddFiles(listboxFiles.Items);
// do the progress bar:
zip.SaveProgress += (sender, e) => {
if (e.EventType == ZipProgressEventType.Saving_BeforeWriteEntry) {
progressBarzipping.PerformStep();
}
};
zip.Save(fs);
}
}

Categories