I have a file which I upload to a temp folder after having done some image resizing as follows:
/uploads/temp/myfile.jpg
How can I read this file into a binary reader as follows if all I have is the file path as indicated above i.e. In the example below I get error:
Error in saving fileSystem.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\\uploads\\temp\\myfile.jpg'
var fs = new FileStream('/uploads/temp/myfile.jpg', FileMode.Open);
using (var reader = new BinaryReader(fs))
{
image.ImageContent = reader.ReadBytes((int)fs.Length);
}
Managed to fix by doing the following:
var fs = new FileStream(HostingEnvironment.MapPath("~/") + "/uploads/temp/myfile.jpg", FileMode.Open);
Related
Can someone tell me what's wrong with my code? I want to zip multiple xml into one file yet the result file is always empty.
using (MemoryStream zipStream = new MemoryStream())
{
using (ZipArchive zip = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
{
string[] xmls = Directory.GetFiles(#"c:\temp\test", "*.xml");
foreach (string xml in xmls)
{
var file = zip.CreateEntry(xml);
using (var entryStream = file.Open())
using (var streamWriter = new StreamWriter(entryStream))
{
streamWriter.Write(xml);
}
}
}
using (FileStream fs = new FileStream(#"C:\Temp\test.zip", FileMode.Create))
{
zipStream.Position = 0;
zipStream.CopyTo(fs);
}
}
See the remarks in the documentation (emphasis mine):
The entryName string should reflect the relative path of the entry you want to create within the zip archive. There is no restriction on the string you provide. However, if it is not formatted as a relative path, the entry is created, but you may get an exception when you extract the contents of the zip archive. If an entry with the specified path and name already exists in the archive, a second entry is created with the same path and name.
You are using an absolute path here:
var file = zip.CreateEntry(xml);
My guess is that when you try to open the archive, it is failing silently to show the entries.
Change your code to use the names of the files without their path:
var file = zip.CreateEntry(Path.GetFileName(xml));
As a separate issue, notice that you're just writing the name of the file to the ZIP entry, rather than the actual file. I imagine you want something like this instead:
var zipEntry = zip.CreateEntry(Path.GetFileName(xml));
using (var entryStream = file.Open())
{
using var fileStream = File.OpenRead(xml);
fileStream.CopyTo(entryStream);
}
I'm working on a project where I want to obtain the file from a compressed archive which only holds a single file. The files I'm interested in opening are of the file extension .als (Ableton Live Set) and from 7Zip I've found they use the gzip compression type.
I've found some code which let's me easily obtain the file from the archive:
using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Read))
{
var entryName = Path.GetFileNameWithoutExtension(txt_file_select.Text);
ZipArchiveEntry entry = archive.GetEntry(entryName);
using (StreamReader reader = new StreamReader(entry.Open()))
{
String fileContent = reader.ReadToEnd();
Debug.WriteLine(fileContent);
}
}
This code opens the file from the stream zipToOpen which has the same filepath as txt_file_select.Text. The single entry that I'm interested in seems to always have the same name as the zipped file itself so this should always give me an entry for any compressed archive that uses zip type. But this code does not accept gzip types in the current state as I get:
Exception thrown: 'System.IO.InvalidDataException' in System.IO.Compression.dll
An exception of type 'System.IO.InvalidDataException' occurred in System.IO.Compression.dll but was not handled in user code
End of Central Directory record could not be found.
I've found that you can open gzip type archives using the GZipStream class. so I added this line:
using (GZipStream zipToOpen = new GZipStream(new FileStream(txt_file_select.Text, FileMode.Open), CompressionMode.Decompress))
which still results in the same exception being thrown. I'm assuming the problem is in converting from GZipStream to ZipArchive.
Here is a simple reproducible example:
using System.Diagnostics;
using System.IO.Compression;
String filepath = #"path\to\als\file.als";
using (GZipStream zipToOpen = new GZipStream(new FileStream(filepath, FileMode.Open), CompressionMode.Decompress))
{
using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Read))
{
var entryName = Path.GetFileNameWithoutExtension(filepath);
ZipArchiveEntry entry = archive.GetEntry(entryName);
using (StreamReader reader = new StreamReader(entry.Open()))
{
String fileContent = reader.ReadToEnd();
Debug.WriteLine(fileContent);
}
}
}
How do I convert the GZipStream into a ZipArchive?
I need to save the file when method OnDestroy is called and load same file when method OnCreate is called. At this time I can read json file easily from Assets (this works fine)
StreamReader reader = new StreamReader(Assets.Open("reiksmes.json"));
string JSONstring = reader.ReadToEnd();
Daiktai myList = JsonConvert.DeserializeObject<Daiktai>(JSONstring);
items.Add(myList);
, but I have some problems when I try to save(write) Daiktai class data to the same file I opened above. I tried:
string data = JsonConvert.SerializeObject(items);
File.WriteAllText("Assets\\reiksmes.json", data);
with this try I get error System.UnauthorizedAccessException: Access to the path "/Assets
eiksmes.json" is denied.
also tried:
string data = JsonConvert.SerializeObject(items);
StreamWriter writer = new StreamWriter(Assets.Open("reiksmes.json"));
writer.WriteLine(data);
and with this try I get error System.ArgumentException: Stream was not writable.
Summary:
I think I chose bad directory(Assets), I need to save and load data (json format). So where do I need to save them and how(give example)?
You can't save anything to assets. You can just read from it. You have to save the file to a different folder.
var fileName = "reiksmes.json";
string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); // Documents folder
var path = Path.Combine(documentsPath, fileName);
Console.WriteLine(path);
if (!File.Exists(path))
{
var s = AssetManager.Open(fileName);
// create a write stream
FileStream writeStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
// write to the stream
ReadWriteStream(s, writeStream);
}
I have a WCF method that I am calling, the method suppose to create a file but it create an exception. I try to find what is in the stream request that I am passing to this method. How I can alert or write this stream so I can find the content. That is my method:
Stream UploadImage(Stream request)
{
Stream requestTest = request;
HttpMultipartParser parser = new HttpMultipartParser(request, "data");
string filePath = "";
string passed = "";
if (parser.Success)
{
// Save the file somewhere
//File.WriteAllBytes(FILE_PATH + title + FILE_EXT, parser.FileContents);
// Save the file
//SaveFile( mtp.Filename, mtp.ContentType, mtp.FileContents);
FileStream fileStream = null;
BinaryWriter writer = null;
try
{
filePath = HttpContext.Current.Server.MapPath("Uploded\\test.jpg"); // BuildFilePath(strFileName, true);
filePath = filePath.Replace("SSGTrnService\\", "");
fileStream = new FileStream(filePath, FileMode.Create);
it produces an error on this line :
fileStream = new FileStream(filePath, FileMode.Create);
that I try to understand why file can not created.
Given the information you gave, I can only assume that your code tries to create the file test.jpg somewhere where your application is not allowed to write. A common mistake would be somewhere in the Program files folder. In modern Windows versions, that is specially protected.
My software needs to generate files on the filesystem that can be read by any other instance of my program, regardless of the user account it's running under. The problem I'm having is that if a file is created under an admin account then I run into an UnauthorizedAccessException when trying to read the contents of the file under a different account. Here's the code I'm using to create the file
using (var fileStream = File.Create(path))
using (var streamWriter = new StreamWriter(fileStream))
{
streamWriter.Write(/*some data*/);
}
and to read from the file
using (var fileStream = new FileStream(fileName, FileMode.Open))
using (var streamReader = new StreamReader(fileStream))
{
var idLine = streamReader.ReadLine();
if (idLine != null) fileContents = idLine;
}
Thanks
If you want to change the access to your file, you have to use the AccessControl : http://msdn.microsoft.com/en-us/library/9c13ttb3.aspx
Call Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) to get an application specific path which is accessible (read/write etc.) by all users/accounts on that computer.