I am developing wpf application. I am using sharpziplib to compress and decompress files. I am easily decompress the .zip files using following code
public static void UnZip(string SrcFile, string DstFile, string safeFileName, int bufferSize)
{
//ICSharpCode.SharpZipLib.Zip.UseZip64.Off;
FileStream fileStreamIn = new FileStream(SrcFile, FileMode.Open, FileAccess.Read);
ZipInputStream zipInStream = new ZipInputStream(fileStreamIn);
string rootDirectory = string.Empty;
if (safeFileName.Contains(".zip"))
{
rootDirectory = safeFileName.Replace(".zip", string.Empty);
}
else
{
rootDirectory = safeFileName;
}
Directory.CreateDirectory(App.ApplicationPath + rootDirectory);
while (true)
{
ZipEntry entry = zipInStream.GetNextEntry();
if (entry == null)
break;
if (entry.Name.Contains("/"))
{
string[] folders = entry.Name.Split('/');
string lastElement = folders[folders.Length - 1];
var folderList = new List<string>(folders);
folderList.RemoveAt(folders.Length - 1);
folders = folderList.ToArray();
string folderPath = "";
foreach (string str in folders)
{
folderPath = folderPath + "/" + str;
if (!Directory.Exists(App.ApplicationPath + rootDirectory + "/" + folderPath))
{
Directory.CreateDirectory(App.ApplicationPath + rootDirectory + "/" + folderPath);
}
}
if (!string.IsNullOrEmpty(lastElement))
{
folderPath = folderPath + "/" + lastElement;
WriteToFile(DstFile + rootDirectory + #"\" + folderPath, bufferSize, zipInStream, rootDirectory, entry);
}
}
else
{
WriteToFile(DstFile + rootDirectory + #"\" + entry.Name, bufferSize, zipInStream, rootDirectory, entry);
}
}
zipInStream.Close();
fileStreamIn.Close();
}
private static void WriteToFile(string DstFile, int bufferSize, ZipInputStream zipInStream, string rootDirectory, ZipEntry entry)
{
FileStream fileStreamOut = new FileStream(DstFile, FileMode.OpenOrCreate, FileAccess.Write);
int size;
byte[] buffer = new byte[bufferSize];
do
{
size = zipInStream.Read(buffer, 0, buffer.Length);
fileStreamOut.Write(buffer, 0, size);
} while (size > 0);
fileStreamOut.Close();
}
But the same code is not working with .bz2 files. It is giving error at line
ZipEntry entry = zipInStream.GetNextEntry();
The error is - Wrong Local header signature: 0x26594131. How should I decompress the .bz2 file ? Can you please provide me any code or link through which I can resolve the above issue ?
While you use a ZipInputStream for .zip files, you should use a BZip2InputStream for .bz2 files (and GZipInputStream for .gz files etc.).
Unlike Zip (and RAR and tar), bz2 and gzip are just byte stream compressors. They have no concept of a container format like the aforementioned, and hence why it fails on GetNextEntry. (In other words, bz2 and gzip will only have 1 entry at most).
Related
As am having my ZIP file in the folder and if I click download report button am blocking to download based on my organization policy.
But I need to download this ZIP file from the code how can we achieve this.
The code which I used as below
string[] filenames = Directory.GetFiles(SourceFolder);
ZipFilePath = DestinationFolder + #"\" + ZipFileName;
using (ZipOutputStream s = new
ZipOutputStream(File.Create(ZipFilePath)))
{
s.SetLevel(6);
byte[] buffer = new byte[4096];
foreach (string file in filenames)
{
if (Path.GetFileName(file).Contains(SubString) || Path.GetFileName(file).Contains("logfile"))
{
ZipEntry entry = new
ZipEntry(Path.GetFileName(file));
entry.DateTime = DateTime.Now;
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();
}
string DownloadFileName = ZipFilePath;
DownloadFileName = DownloadFileName.Replace("\\", "~");
RadAjaxManager1.ResponseScripts.Add("setTimeout(function(){ document.location.href = 'DownloadHandler.ashx?FileName=" + DownloadFileName + "'; return false; },300);");
The DownloadHandler.ashx page as below
public void ProcessRequest(HttpContext context)
{
try
{
HttpResponse rspns = context.Response;
string FileToDownload = context.Request.QueryString["FileName"];
string FileName = string.Empty;
if (context.Request.QueryString["Name"] != null)
{
FileName = context.Request.QueryString["Name"];
}
if (FileToDownload!=null)
{
FileToDownload = FileToDownload.Replace("~", "\\");
FileName = System.IO.Path.GetFileName(FileToDownload);
}
else
{
//FileName = Convert.ToString(iTAPSession.UserData);
}
rspns.AppendHeader("content-disposition", "attachment; filename=\"" + FileName.Replace(" ", "%20"));
rspns.TransmitFile(FileToDownload);
rspns.End();
}
catch (Exception e)
{
}
}
public bool IsReusable
{
get
{
return false;
}
}
am getting the below exception
Based on your organization's access policies, access to this website or download ( http://xxxxxxx/ITAADemo/DownloadHandler.ashx?FileName=D:~ITAADemo~Files~SuperAdmin~bn4wgrusef1xgmjhqokd2yo2~~TextAnalytics~~zipdownload~Report_2018-Jul-19-11-39-31.zip ) has been blocked because the file type "application/zip" is not allowed.
I'm trying to convert a stream to image using C#, but the image is appearing corrupt.
Here is how i'm getting the BaseString representation
byte[] imageArray = System.IO.File.ReadAllBytes(#"C:\Users\jay.raj\Desktop\images\images\tiger.jpg");
string base64ImageRepresentation = Convert.ToBase64String(imageArray);
Now I'm passing this to a function which converts it into Stream and tries to convert it into image file.
byte[] byteArray = Encoding.ASCII.GetBytes(mySettingInfo.FileToUpload);
MemoryStream stream = new MemoryStream(byteArray);
UtilityHelper.UploadImageFormDevice(stream, ref ss);
Here is the UploadImageFormDevice function:
public static ResponseBase UploadImageFormDevice(Stream image, ref string imageName)
{
ResponseBase rep = new ResponseBase();
try
{
string filname = imageName;
string filePath = #"C:\Users\jay.raj\Desktop\Upload\";
if (filname == string.Empty)
filname = Guid.NewGuid().ToString() + ".jpg";
filePath = filePath + "\\" + filname;
FileStream fileStream = null;
using (fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
{
const int bufferLen = 1024;
byte[] buffer = new byte[bufferLen];
int count = 0;
while ((count = image.Read(buffer, 0, bufferLen)) > 0)
{
fileStream.Write(buffer, 0, count);
}
fileStream.Close();
image.Close();
}
imageName = filname;
}
catch (Exception ex)
{
rep.Code = 1000;
rep.Message = "Server Error";
}
return rep;
}
As #naivists wrote try replace this line:
byte[] byteArray = Encoding.ASCII.GetBytes(mySettingInfo.FileToUpload);
To this line:
byte[] byteArray = Convert.FromBase64String(mySettingInfo.FileToUpload);
It looks like you want to transfer a file from #"C:\Users\jay.raj\Desktop\images\images\tiger.jpg" to #"C:\Users\jay.raj\Desktop\Upload\" + "\\" + Guid.NewGuid().ToString() + ".jpg".
In your case you read the file as a byte array, convert it into a base 64 coded string and then again into a byte array. This is unnecessary and error prone. In your case you missed the decoding.
If you ignore for a moment that it is an image and see it just as a bunch of bytes things might get easier.
string srcPath = #"C:\Users\jay.raj\Desktop\images\images\tiger.jpg";
string dstPath = #"C:\Users\jay.raj\Desktop\Upload\" + "\\" + Guid.NewGuid().ToString() + ".jpg";
byte[] imageArray = System.IO.File.ReadAllBytes(srcPath);
System.IO.File.WriteAllBytes(dstPath, imageArray);
I want to take (upload) a file to a specific folder that I have created in my project (on local computer not a server!).
Here is the code that I am using:
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(Server.MapPath("images/" + filename));
I have added the Fileupload, and the code above in a button. But the code won't work. What's the problem?
I also used this form:
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(Server.MapPath("~DesktopModules/UshtrimiDyte/images/" + filename));
I also used it with double back slashes, but that didn't work either. How can I solve my problem?
Try the above
string path = Server.MapPath("~DesktopModules/UshtrimiDyte/images/" + filename);
System.IO.Stream myStream;
Int32 fileLen;
byte[] Input = null;
fileLen = FileUpload1.PostedFile.ContentLength;
if (fileLen > 0)
{
Input = new Byte[fileLen];
myStream = FileUpload1.FileContent;
myStream.Read(Input, 0, fileLen);
string I_Docx_type = FileUploadFieldDoc.FileName.Substring(FileUpload1.FileName.LastIndexOf(".") + 1);
WriteToFile(path + "." +I_Docx_type, ref Input);
path += "." + I_Docx_type;
}
method
private void WriteToFile(string strPath, ref byte[] Buffer)
{
// Create a file
System.IO.FileStream newFile = new System.IO.FileStream(strPath, System.IO.FileMode.Create);
// Write data to the file
newFile.Write(Buffer, 0, Buffer.Length);
// Close file
newFile.Close();
}
I use this simple code for log files.
private string LogFile
{
get
{
if (String.IsNullOrEmpty(this.LogFile1))
{
string fn = "\\log.txt";
int count = 0;
while (File.Exists(fn))
{
fn = fn + "(" + count++ + ").txt";
}
this.LogFile1 = fn;
}
return this.LogFile1;
}
}
How can I move every log file into another directory ( folder ) and make it archive like .zip?
This will run once per and I will have one file per day.
File moving:
public static void Move()
{
string path = "";
string path2 = "";
try
{
if (!File.Exists(path))
{
using (FileStream fs = File.Create(path)) { }
}
if (File.Exists(path2))
File.Delete(path2);
File.Move(path, path2);
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
For move files, you can use the static method Move of File class. And for zip files, you can look at GZipStream or ZipArchive class.
If you want windows zipping.
Then check this out :
https://msdn.microsoft.com/en-us/library/system.io.compression.zipfile(v=vs.110).aspx
using System;
using System.IO;
using System.IO.Compression;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
string startPath = #"c:\example\start";
string zipPath = #"c:\example\result.zip";
string extractPath = #"c:\example\extract";
ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);
}
}
}
// for moving
File.Move(SourceFile, DestinationFile); // store in dateTime directory to move file.
//method for zip file
private static void CompressFile(string path)
{
FileStream sourceFile = File.OpenRead(path);
FileStream destinationFile = File.Create(path + ".gz");
byte[] buffer = new byte[sourceFile.Length];
sourceFile.Read(buffer, 0, buffer.Length);
using (GZipStream output = new GZipStream(destinationFile,
CompressionMode.Compress))
{
Console.WriteLine("Compressing {0} to {1}.", sourceFile.Name,
destinationFile.Name, false);
output.Write(buffer, 0, buffer.Length);
}
// Close the files.
sourceFile.Close();
destinationFile.Close();
}
I have a small upload application where i upload a file using a webservice (asmx), check the MD5 and verify it. Problem is that when i verify the file it says that the file is locked by another process. Below is my code for uploading and verifying:
private static object padlock = new object();
Chunking the upload file in smaller bites and uploading each of them
[WebMethod]
public void LargeUpload(byte[] content, string uniqueName)
{
lock (padlock)
{
string path = Server.MapPath(PartialDir + "/" + uniqueName);
BinaryWriter writer = new BinaryWriter(File.Open(path, FileMode.Append, FileAccess.Write));
writer.Write(content);
writer.Flush();
writer.Close();
writer = null;
}
}
After the last one insert it into my database. After this the client verifies the file by requesting the MD5:
[WebMethod]
public int EndLargeUpload(string name, int folderId, long length, string uniqueName, int customerid)
{
lock (padlock)
{
string path = Server.MapPath(PartialDir + "/" + uniqueName);
string newPath = Server.MapPath(RepositoryDir + "/" + uniqueName);
File.Copy(path, newPath);
//delete partial
File.Delete(path);
string extension = Path.GetExtension(uniqueName);
string newFileName = uniqueName;
GWFile newFile = new GWFile();
newFile.DiscName = newFileName;
newFile.FileName = name;
newFile.FolderId = folderId;
newFile.Description = "";
newFile.Size = (int)length;
newFile.DiscFolder = Server.MapPath("/Repository");
newFile.DiscRelativePath = "/Repository/" + newFile.DiscName;
newFile.CustomerId = customerid;
IGWFileRepository fileRepository = ObjectFactory.GetInstance<IGWFileRepository>();
fileRepository.SaveFile(newFile);
return newFile.Id;
}
}
After the EndLargeUpload() method the client calls the RequestMD5 method with the id of the file, this call excepts with an exception that it cannot open the file ".....xxx..." because it s being used by another process...
private string GetMD5HashFromFile(string fileName)
{
lock (padlock)
{
using (FileStream file = new FileStream(fileName, FileMode.Open)) // <-- excepts here
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] retVal = md5.ComputeHash(file);
file.Close();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < retVal.Length; i++)
{
sb.Append(retVal[i].ToString("x2"));
}
return sb.ToString();
}
}
}
I used the process explorer from sysinternals to view the file, it says that the file is locked by the web server ( pls refer to this img: http://screencast.com/t/oqvqWXLjku) - how can the web server lock it? can I work around this?
How about the last two lines in the EndLargeUpload method:
IGWFileRepository fileRepository = ObjectFactory.GetInstance<IGWFileRepository>();
fileRepository.SaveFile(newFile);
Is it possible that IGWFileRepository.SaveFile() is not closing the file properly?
Switched to IIS, and the problem seems to go away...