I have an image file in Canvas element that I get in code behind in asp.net. now I want to save it to a folder in my project but file stream always saves it to c drive. What do I do?
[WebMethod()]
public void SaveUser(string imageData)
{
//Create image to local machine.
string fileNameWitPath = path + "4200020789506" + ".png";
using (FileStream fs = new FileStream(fileNameWitPath, FileMode.Create))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
byte[] data = Convert.FromBase64String(imageData);
bw.Write(data);
bw.Close();
}
}
// Save fileNameWitPath variable to Database.
}
Here is an example of how I save files to an Images folder in my project directory.
var fileName = "4200020789506.png";
var base64String = SOME_REALLY_LONG_STRING;
using (var s = new MemoryStream(Convert.FromBase64String(base64String)))
using (var f = new FileStream(Path.Combine(Server.MapPath("~/Images"), fileName), FileMode.Create, FileAccess.Write))
{
s.CopyTo(f);
}
Here's what I do and it works well. For you, filePath/filename = fileNameWitPath. Do this for each file you have. Hope it works for you. If you need further info, Id be glad to help.
using (var stream = File.Create(filePath + filename))
{
attachment.ContentObject.DecodeTo(stream, cancel.Token);
}
I can only imagine your path variable points to your C:\ drive.
You need to set the path variable equal to the location you want, for instance:
public void SaveUser(string imageData)
{
path = #"C:\YourCustomFolder\"; // your path needs to point to the Directory you want to save
//Create image to local machine.
string fileNameWitPath = path + "4200020789506" + ".png";
//chekc if directory exist, if not, create
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
using (FileStream fs = new FileStream(fileNameWitPath, FileMode.Create))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
byte[] data = Convert.FromBase64String(imageData);
bw.Write(data);
bw.Close();
}
}
// Save fileNameWitPath variable to Database.
}
I also included a Check to see if your directory exists, and if it does not, it will create a folder called 'YourCustomFolder' on your C drive, where it will save images.
If you would like to save your image to a folder in your project, I would recommend using Server.MapPath(~/YourFolderInApplication)
Related
using Ionic.Zip;
var savedzipFile = "C:\alldocs\issues\issuesfromtoday.zip";
var selectedfolderfromDialog = "D:\MyDocs";
This is what I have. I cant use webblient because its not a url. How to I save the zip file to that selected folder location? Zip file has PDFs if that matters.
This should do the trick:
var savedzipFile = #"C:\alldocs\issues\issuesfromtoday.zip";
var selectedfolderfromDialog = #"D:\MyDocs";
using (var sourceStream = System.IO.File.Open(savedzipFile, System.IO.FileMode.Open))
{
using (var targetStream = System.IO.File.OpenWrite(selectedfolderfromDialog + #"\" + savedzipFile.Substring(savedzipFile.LastIndexOf('\\'))))
{
sourceStream.CopyTo(targetStream);
}
}
I want to save multiple files in one Zip file on my disc. This Zip is created but his type is "Compressed (zipped) Folder" and is impossible to open. Error: "Windows cannot open the folder. The Compressed (zipped) Folder 'path' is invalid. Can I make it normal .Zip file somehow?
int i = 0;
await using var ms = new MemoryStream();
{
using var archive = new ZipArchive(ms, ZipArchiveMode.Create, true);
{
foreach (var s in stepwiseData)
{
//streamWriter.Write(s);
var entry = archive.CreateEntry($"Name {i.ToString()}");
i++;
using (BinaryWriter writer = new BinaryWriter(entry.Open()))
{
writer.Write(s.ToArray());
}
}
var folder = #"C:\Temp\test\";
var fileName = "TestName.zip";
var fullPath = folder + fileName;
var bytes = ms.ToArray();
File.WriteAllBytes(fullPath, bytes);
}
}
I have a function that requires a Filestream as input.
I want to hand several Files to that function which I get from uploaded zip-Files.
Is it possible to create the Filestream without extracting the file to a temporary folder?
I imagin something like this:
string path = #"C:\somepathtomyzip";
string filepath = "nameofimagefile"
using (ZipArchive archive = ZipFile.OpenRead(path))
{
ZipArchiveEntry entry = archive.GetEntry(file_path);
//generate Filestream from entry
myFunction(filestreamIneed);
}
You can use ZipArchiveEntry.Open() and copy the output from the returned Stream instance to a FileStream instance:
using (ZipArchive archive = ZipFile.OpenRead(path))
{
ZipArchiveEntry entry = archive.GetEntry(file_path);
var memoryStream = return entry.Open();
using (var fileStream = new FileStream(fileName, FileMode.CreateNew, FileAccess.ReadWrite))
{
memoryStream.CopyTo(fileStream); // fileStream is not populated
}
}
Inside my app, I am trying to download about 180 small audio files all at once. I tried the BackgroundTransferService, but it does not seem stable with so many small files. So, now I am downloading a ZIP of all those audio and want extract them in "audio" folder. I tried the method in this thread:
How to unzip files in Windows Phone 8
But I get this error: 'System.IO.IOException' occurred in mscorlib.ni.dll... in the following code. How can I overcome this issue?
while (reader.ReadInt32() != 101010256)
{
reader.BaseStream.Seek(-5, SeekOrigin.Current); // this line causes error
}...
Also, where do I need to place this code and where do I give it the destination directory?
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(#"audio.rar", FileMode.Open, FileAccess.ReadWrite))
{
UnZipper unzip = new UnZipper(fileStream);
foreach (string filename in unzip.FileNamesInZip())
{
string FileName = filename;
}
}
Use Silverlight SharpZipLib. Add SharpZipLib.WindowsPhone7.dll to your project (works on WP8 silverlight also).
private void Unzip()
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
ZipEntry entry;
int size;
byte[] data = new byte[2048];
using (ZipInputStream zip = new ZipInputStream(store.OpenFile("YourZipFile.zip", FileMode.Open)))
{
// retrieve each file/folder
while ((entry = zip.GetNextEntry()) != null)
{
if (!entry.IsFile)
continue;
// if file name is music/rock/new.mp3, we need only new.mp3
// also you must make sure file name doesn't have unsupported chars like /,\,etc.
int index = entry.Name.LastIndexOf('/');
string name = entry.Name.Substring(index + 1);
// create file in isolated storage
using (var writer = store.OpenFile(name, FileMode.Create))
{
while (true)
{
size = zip.Read(data, 0, data.Length);
if (size > 0)
writer.Write(data, 0, size);
else
break;
}
}
}
}
}
}
There are several 3rd party libraries in order to extract ZIP files in WP8 like the ZipLib which you can download from # http://slsharpziplib.codeplex.com/
however DotNetZip a parent ZipLib and much more stable.
Here is a sample code. Not checked if it works, but this is how you go at it.
ZipFile zip = ZipFile.Read(ZipFileToUnzip);
foreach (ZipEntry ent in zip)
{
ent.Extract(DirectoryWhereToUnizp, ExtractExistingFileAction.OverwriteSilently);
}
I have just solved this. what you can do is use this method and your file will go save to isolated storage in proper folder structure as present in your zip file. you can change according to your need where you want to store the data.
I have just read a sample.zip file. From your app folder.
private async Task UnZipFile()
{
var myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
using (var fileStream = Application.GetResourceStream(new Uri("sample.zip", UriKind.Relative)).Stream)
{
var unzip = new UnZipper(fileStream);
foreach (string filename in unzip.FileNamesInZip)
{
if (!string.IsNullOrEmpty(filename))
{
if (filename.Any(m => m.Equals('/')))
{
myIsolatedStorage.CreateDirectory(filename.Substring(0, filename.LastIndexOfAny(new char[] { '/' })));
}
//save file entry to storage
using (var streamWriter =
new StreamWriter(new IsolatedStorageFileStream(filename,
FileMode.Create,
FileAccess.ReadWrite,
myIsolatedStorage)))
{
streamWriter.Write(unzip.GetFileStream(filename));
}
}
}
}
}
cheers :)
I need help in converting a file received from a jquery ajax to byte array. I'm using a plugin called ajaxfileupload then from a jquery ajax call I send a file from a fileupload control to a handler. Here is my
handler code:
if (context.Request.Files.Count > 0)
{
string path = context.Server.MapPath("~/Temp");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
var file = context.Request.Files[0];
string fileName;
if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
{
string[] files = file.FileName.Split(new char[] { '\\' });
fileName = files[files.Length - 1];
}
else
{
fileName = file.FileName;
}
string fileType = file.ContentType;
string strFileName = fileName;
FileStream fs = new FileStream("~/Temp/" + strFileName, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] imagebytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();
DBAccess dbacc = new DBAccess();
dbacc.saveImage(imagebytes);
string msg = "{";
msg += string.Format("error:'{0}',\n", string.Empty);
msg += string.Format("msg:'{0}'\n", strFileName);
msg += "}";
context.Response.Write(msg);
}
I'm saving the file to a folder within a project then trying to retrieve that file and save it to the database. I can assure you that the image is being saved to the temp folder. The problem is with the line with (*) the file path is wrong. This is the file path that is being retrieved. "'C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\~\Temp\2012-06-03 01.25.47.jpg'.". The temp folder is located locally inside my project and I want to retrieved the image within that folder. How can I set the file path to my desired location? Or is there another way to convert a file to byte array after retrieving it from a jquery ajax call?
Credits to these articles:
Save and Retrieve Files from SQL Server Database using ASP.NET
Async file upload with jQuery and ASP.NET
Just these 3 lines will do:
int filelength = file.ContentLength;
byte[] imagebytes = new byte[filelength ];
file.InputStream.Read(imagebytes , 0, filelength );
using (var stream = upload.InputStream)
{
// use stream here: using StreamReader, StreamWriter, etc.
}