How to create zip file in asp.net - asp.net

I need to create zip file from the folder, path:
D:\Nagaraj\New Project Read Document\TCBILPOS\TCBILPOS\TCBILPOS\FileBuild\HOST
within that host folder there are 7 txt files.
I want to create zip file HOST.zip in the folder above:
D:\Nagaraj\New Project Read Document\TCBILPOS\TCBILPOS\TCBILPOS\FileBuild

I've used Ionic ZIP for this in our own projects.
using (ZipFile zip = new ZipFile())
{
// add this map file into the "images" directory in the zip archive
zip.AddFile("c:\\images\\personal\\7440-N49th.png", "images");
// add the report into a different directory in the archive
zip.AddFile("c:\\Reports\\2008-Regional-Sales-Report.pdf", "files");
zip.AddFile("ReadMe.txt");
zip.Save("MyZipFile.zip");
}

public class Ziper
{
public static string MapPathReverse(string fullServerPath)
{
return #"~\" + fullServerPath.Replace(HttpContext.Current.Request.PhysicalApplicationPath, String.Empty);
}
public static void Zip(HttpResponse Response, HttpServerUtility Server, string[] pathes)
{
Response.Clear();
Response.BufferOutput = false; // false = stream immediately
System.Web.HttpContext c = System.Web.HttpContext.Current;
//String ReadmeText = String.Format("README.TXT\n\nHello!\n\n" +
// "This is text for a readme.");
string archiveName = String.Format("archive-{0}.zip",
DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "filename=" + archiveName);
var path = Server.MapPath(#"../Images/TempFile/TempFile" + DateTime.Now.Ticks);
if (Directory.Exists(path) == false)
Directory.CreateDirectory(path);
var pathzipfile = Server.MapPath(#"../Images/TempFile/zip_" + DateTime.Now.Ticks + ".zip");
for (int i = 0; i < pathes.Length; i++)
{
if (File.Exists(pathes[i]))
{
string dst = Path.Combine(path, Path.GetFileName(pathes[i]));
File.Copy(pathes[i], dst);
}
}
if (File.Exists(pathzipfile))
File.Delete(pathzipfile);
ZipFile.CreateFromDirectory(path, pathzipfile);
{
byte[] bytes = File.ReadAllBytes(pathzipfile);
Response.OutputStream.Write(bytes, 0, bytes.Length);
}
Response.Close();
File.Delete(pathzipfile);
Directory.Delete(path, true);
}
public Ziper()
{
}
}

Related

ASP.NET core with MVC folder pathing/mapping FAIL

Whenever I upload a file I want to have it automatically converted into .pdf (I am doing that using NuGet). The thing is the upload scheme is done using relative paths. I do not know what to put into these parentheses:
var wordDocument = appWord.Documents.Open(uploadedFile);
What should I replace uploadedFile with in order to work? I will leave my relative path mapping code below:
public IActionResult Index1()
{
// Get files from the server
var model = new FilesViewModel();
foreach (var item in Directory.GetFiles(Path.Combine(Directory.GetCurrentDirectory(), "upload")))
{
model.Files.Add(
new FileDetails { Name = System.IO.Path.GetFileName(item), Path = item });
}
return View(model);
}
[HttpPost]
public IActionResult Index1(IFormFile[] files)
{
// Iterate each files
foreach (var file in files)
{
// Get the file name from the browser
var fileName = System.IO.Path.GetFileName(file.FileName);
// Get file path to be uploaded
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "upload", fileName);
// Check If file with same name exists and delete it
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
}
// Create a new local file and copy contents of uploaded file
using (var localFile = System.IO.File.OpenWrite(filePath))
using (var uploadedFile = file.OpenReadStream())
{
var appWord = new Application();
if (appWord.Documents != null)
{
//yourDoc is your word document
var wordDocument = appWord.Documents.Open(uploadedFile);
string pdfDocName = "pdfDocument.pdf";
if (wordDocument != null)
{
wordDocument.ExportAsFixedFormat(pdfDocName,
WdExportFormat.wdExportFormatPDF);
wordDocument.Close();
}
appWord.Quit();
}
uploadedFile.CopyTo(localFile);
}
}
ViewBag.Message = "Files are successfully uploaded";
// Get files from the server
var model = new FilesViewModel();
foreach (var item in Directory.GetFiles(Path.Combine(Directory.GetCurrentDirectory(), "upload")))
{
model.Files.Add(
new FileDetails { Name = System.IO.Path.GetFileName(item), Path = item });
}
return View(model);
}
public async Task<IActionResult> Download(string filename)
{
if (filename == null)
return Content("filename is not availble");
var path = Path.Combine(Directory.GetCurrentDirectory(), "upload", filename);
var memory = new MemoryStream();
using (var stream = new FileStream(path, FileMode.Open))
{
await stream.CopyToAsync(memory);
}
memory.Position = 0;
return File(memory, GetContentType(path), Path.GetFileName(path));
}
private string GetContentType(string path)
{
var types = GetMimeTypes();
var ext = Path.GetExtension(path).ToLowerInvariant();
return types[ext];
}
private Dictionary<string, string> GetMimeTypes()
{
return new Dictionary<string, string>
{
{".txt", "text/plain"},
{".pdf", "application/pdf"},
{".doc", "application/vnd.ms-word"},
{".docx", "application/vnd.ms-word"},
{".xls", "application/vnd.ms-excel"},
{".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
{".png", "image/png"},
{".jpg", "image/jpeg"},
{".jpeg", "image/jpeg"},
{".gif", "image/gif"},
{".csv", "text/csv"}
};
}

Xamarin Forms Labs Camera - Permanently Saving Images and Calling Them

I got the camera function to work and it displays the image on the page like i asked it too. But is there a way to permanently save the image on your phone or somewhere else and then call it?
Thank you so much
Here's some code that works for me.
IFileAccess is my wrapper around System.IO.File functions such as file open, write, check if exsists. If you're making your own file service look up Xamarin.Forms.Labs.Resolver and how to use it; if you're using shared Forms project type you can access System.IO.File directly from the Forms project. Assuming that's clear, the following
var fileAccess = Resolver.Resolve<IFileAccess> ();
mediaPicker.SelectPhotoAsync (new CameraMediaStorageOptions{ MaxPixelDimension = 1024 })
.ContinueWith(t=>{
if (!t.IsFaulted && !t.IsCanceled) {
var mediaFile = t.Result;
var fileAccess = Resolver.Resolve<IFileAccess> ();
string imageName = "IMG_" + DateTime.Now.ToString ("yy-MM-dd_HH-mm-ss") + ".jpg";
// save the media stream to a file
fileAccess.WriteStream (imageName, mediaFile.Source);
// use the stored file for ImageSource
ImageSource imgSource = ImageSource.FromFile (fileAccess.FullPath (imageName));
imgInXAML.Source = imgSource;
}
});
Further detail on IFileAccess.
In your Forms project create an interface like this:
public interface IFileAccess
{
bool Exists (string filename);
string FullPath(string filename);
void WriteStream (string filename, Stream streamIn);
}
In your iOS or Android or Shared project add a class FileAccess that implements IFileAccess:
public class FileAccess : IFileAccess
{
public bool Exists (string filename)
{
var filePath = GetFilePath (filename);
if (File.Exists (filePath)) {
FileInfo finf = new FileInfo (filePath);
return finf.Length > 0;
} else
return false;
}
public string FullPath (string filename)
{
var filePath = GetFilePath (filename);
return filePath;
}
static string GetFilePath (string filename)
{
var documentsPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
var filePath = Path.Combine (documentsPath, filename);
return filePath;
}
public void WriteStream (string filename, Stream streamIn)
{
var filePath = GetFilePath (filename);
using (var fs = File.Create (filePath)) {
streamIn.CopyTo (fs);
}
}
}
If you're already using Xamarin.Forms.Labs.Resolver then add only the line to register the service, otherwise in your iOS or Android project find a call to Forms.Init() and right before it add
var resolverContainer = new SimpleContainer ();
resolverContainer.Register<IFileAccess> (t => new FileAccess ()); // maybe just this line
Resolver.SetResolver (resolverContainer.GetResolver ());

How to write binary to file

I have code that's supposed to read binary values from the database and convert it into a zip file. It only creates a file that's 43kb big and it can't be extracted. What am I missing?
com = new SqlCommand("SELECT BinFile FROM tbl_reports WHERE DBKey=411", conString);
byte[] blob = (byte[])com.ExecuteScalar();
File.WriteAllBytes("C:\\" + "test.zip", blob);
Use DotNetZip , here is example .
using (ZipFile zip = new ZipFile())
{
zip.Password = pwd;
zip.AddFile(saveFileDialog1.FileName + ".xml");
zip.Save(saveFileDialog1.FileName + ".zip");
}
Additionally , I think you need to convert byte[] to string and then text file .
You can use convert.frombase64string method !
Edit
If you want to write byte[] to file , use this function ,
public bool ByteArrayToFile(string _FileName, byte[] _ByteArray)
{
try
{
System.IO.FileStream _FileStream =
new System.IO.FileStream(_FileName, System.IO.FileMode.Create,
System.IO.FileAccess.Write);
_FileStream.Write(_ByteArray, 0, _ByteArray.Length);
_FileStream.Close();
return true;
}
catch (Exception _Exception)
{
Console.WriteLine("Exception caught in process: {0}",
_Exception.ToString());
}
return false;
}
And call this function likes
com = new SqlCommand("SELECT BinFile FROM tbl_reports WHERE DBKey=411", conString);
byte[] blob = (byte[])com.ExecuteScalar();
ByteArrayToFile("C:\\test.txt",blob);

File not found exception once deployed to Server

I am using the below code to Upload an Image file to a SharePoint Document Library. The code works fine locally but once deployed to server, i get the Exception as file not found.
String fileToUpload = FlUpldImage.PostedFile.FileName; //#"C:\Users\admin.RSS\Desktop\Photos\me_skype.jpg";
String documentLibraryName = "SiteAssets";
if (!System.IO.File.Exists(fileToUpload))
throw new FileNotFoundException("File not found.", fileToUpload);
SPFolder myLibrary = web.Folders[documentLibraryName];
// Prepare to upload
Boolean replaceExistingFiles = true;
String fileName = CheckStringNull(txtFirstName.Text) + CheckStringNull(txtLastName.Text) + CheckDateNull(txtDOB) + System.IO.Path.GetFileName(fileToUpload); ;
if (fileName.Contains('/'))
{
fileName = fileName.Replace("/", "");
}
if (fileName.Contains(':'))
{
fileName = fileName.Replace(":", "");
}
FileStream fileStream = File.OpenRead(fileToUpload);
//Upload document
SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);
string url = site.ToString() + "/" + spfile.ToString();
if (url.Contains("="))
{
url = url.Split('=')[1];
}
//Commit
myLibrary.Update();
The string fileupload contains URL as C:\Users\admin.RSS\Desktop\Photos\me.jpg This URL is actually the client system and the server side code throws exception as file not found. How to handle this issue?
UPDATE:
I removed the lines of code that checks if the file exists and now i get the exeption on FileStream fileStream = File.OpenRead(fileToUpload); as c:\windows\system32\inetsrv\20120605_133145.jpg cold not be found
Kindly help. Thank You
if (this.fuAvatarUpload.HasFile && this.fuAvatarUpload.PostedFile.FileName.Length > 0)
{
string extension = Path.GetExtension(file.FileName).ToLower();
string mimetype;
switch (extension)
{
case ".png":
case ".jpg":
case ".gif":
mimetype = file.ContentType;
break;
default:
_model.ShowMessage("We only accept .png, .jpg, and .gif!");
return;
}
if (file.ContentLength / 1000 < 1000)
{
Image image = Image.FromStream(file.InputStream);
Bitmap resized = new Bitmap(image, 150, 150);
byte[] byteArr = new byte[file.InputStream.Length];
using (MemoryStream stream = new MemoryStream())
{
resized.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
byteArr = stream.ToArray();
}
file.InputStream.Read(byteArr, 0, byteArr.Length);
profile.ImageUrl = byteArr;
profile.UseGravatar = false;
profileService.UpdateProfile(profile);
this._model.ShowApprovePanel();
}
else
{
_model.ShowMessage("The file you uploaded is larger than the 1mb limit. Please reduce the size of your file and try again.");
}
}
Saving the file physically onto server and than working on the same helped me resolve my issue.

Dynamically change colour of KML polygon in Google Maps API v3

I'm using Google Maps v3 API to load a KML layer and want to be able to change the colour of the KML from its default blue without having to edit the KML file itself. Is this possible using JavaScript or some other means?
Unfortunately can't post a link, but it's pretty standard stuff.
var map = new google.maps.Map(document.getElementById("mymap"), { some options });
var regionLayer = new google.maps.KmlLayer("http://.../some.kml");
regionLayer.setMap(map);
From my understanding of the documentation, 'no', but it's not especially clear. I'm trying to do a similar thing (but update the colour of mouseover/mouseout).
The KML file is loaded by the Google servers, parsed and sent along to your javascript object to be applied to the map, so, by the time your javascript KMLLayer sees it, it's all sorted out.
You may be able to do something with Styles and styleUrl. This is supposed to allow you to set a number of different styles that can then be applied at runtime, however, I haven't got it working.
I have done this by creating a web service which reads in a KML file to a string, inserts a style section to the beginning of the KML string, and also a styleURL to each uniquely named placemark. It's fairly simple to amend the markup using a .net web service and write it back out to the server you have hosting the web service.
For example this uses a class which contains placemark IDs and a colour flag:
public string KMLStyler(string URL, string URLName, Data[] MyData)
{
try
{
ReadFile(URL);
string NewKML = ReadFile(URL);
string RedStyle = "<Style id=\"red\"><LineStyle><color>7F7F7F7F</color><width>2</width></LineStyle><PolyStyle><color>7F0000FF</color><fill>1</fill><outline>1</outline></PolyStyle></Style>";
string BlackStyle = "<Style id=\"black\"><LineStyle><color>7F7F7F7F</color><width>2</width></LineStyle><PolyStyle><color>7F7F7F7F</color><fill>1</fill><outline>1</outline></PolyStyle></Style>";
string GreenStyle = "<Style id=\"green\"><LineStyle><color>7F7F7F7F</color><width>2</width></LineStyle><PolyStyle><color>7F00FF00</color><fill>1</fill><outline>1</outline></PolyStyle></Style>";
string BlueStyle = "<Style id=\"blue\"><LineStyle><color>7F7F7F7F</color><width>2</width></LineStyle><PolyStyle><color>7F7F7F7F</color><fill>1</fill><outline>1</outline></PolyStyle></Style>";
//add styles to top
int EndID = 0;
EndID = NewKML.IndexOf("</name>") + 7;
NewKML = NewKML.Insert(EndID, RedStyle);
EndID = NewKML.IndexOf("</name>") + 7;
NewKML = NewKML.Insert(EndID, BlackStyle);
EndID = NewKML.IndexOf("</name>") + 7;
NewKML = NewKML.Insert(EndID, GreenStyle);
EndID = NewKML.IndexOf("</name>") + 7;
NewKML = NewKML.Insert(EndID, BlueStyle);
//add each style to each placemark
foreach (Data MyDataSingle in MyData)
{
int NamePos = NewKML.IndexOf(MyDataSingle.Name);
if (NamePos == -1) throw new Exception("Did not find '" + MyDataSingle.Name + "' within File");
NamePos += MyDataSingle.Name.Length + 7;
int MultiGeometryStartPos = NewKML.IndexOf("<MultiGeometry>", NamePos);
int MultiGeometryEndPos = NewKML.IndexOf("</MultiGeometry>", NamePos);
int PolygonStartPos = NewKML.IndexOf("<Polygon>", NamePos);
int InsertPos = 0;
if (MultiGeometryStartPos < PolygonStartPos)
{
if (MultiGeometryStartPos != -1)
{
InsertPos = MultiGeometryStartPos;
}
else
{
InsertPos = PolygonStartPos;
}
}
else
{
InsertPos = PolygonStartPos;
}
if (MyDataSingle.Red)
{
NewKML = NewKML.Insert(InsertPos, "<styleUrl>#red</styleUrl>");
}
if (MyDataSingle.Black)
{
NewKML = NewKML.Insert(InsertPos, "<styleUrl>#black</styleUrl>");
}
if (MyDataSingle.Green)
{
NewKML = NewKML.Insert(InsertPos, "<styleUrl>#green</styleUrl>");
}
if (MyDataSingle.Blue)
{
NewKML = NewKML.Insert(InsertPos, "<styleUrl>#blue</styleUrl>");
}
}
string NewFileName = WriteFile(NewKML, URLName);
return NewFileName;
}
catch (Exception ex)
{
return ex.ToString();
}
}
public string WriteFile(string KMLData, string URLName)
{
string FileName = "http:\\blah.co.uk\blah.kml";
StreamWriter writer = new StreamWriter("C:/inetpub/blah.kml");
writer.Write(KMLData);
writer.Flush();
writer.Close();
return FileName;
}
public string ReadFile(string URL)
{
string File = "";
StreamReader reader = new StreamReader(WebRequest.Create(URL).GetResponse().GetResponseStream());
string line;
while ((line = reader.ReadLine()) != null)
{
File += line;
}
return File;
}

Resources