Store Image in .resx as byte[] rather than Bitmap - c#

Slightly daft, but...
Is there a way to prevent Visual Studio treating a .jpg file in a .resx as a Bitmap so that I can access a byte[] property for the resource instead?
I just want:
byte[] myImage = My.Resources.MyImage;

Alternatively, right click on your .resx file and click "View Code".
Edit the XML resource item to use System.Byte[] like this:
<data name="nomap" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\nomap.png;System.Byte[]</value>
</data>
Save and you should be able to use Byte[] instead of Bitmap

Try using an "Embedded Resource" instead
So lets say you have a jpg "Foo.jpg" in ClassLibrary1. Set the "Build Action" to "Embedded Resource".
Then use this code to get the bytes
byte[] GetBytes()
{
var assembly = GetType().Assembly;
using (var stream = assembly.GetManifestResourceStream("ClassLibrary1.Foo.jpg"))
{
var buffer = new byte[stream.Length];
stream.Read(buffer, 0, (int) stream.Length);
return buffer;
}
}
Or, alternatively, if you want a more re-usable method
byte[] GetBytes(string resourceName)
{
var assembly = GetType().Assembly;
var fullResourceName = string.Concat(assembly.GetName().Name, ".", resourceName);
using (var stream = assembly.GetManifestResourceStream(fullResourceName))
{
var buffer = new byte[stream.Length];
stream.Read(buffer, 0, (int) stream.Length);
return buffer;
}
}
and call
var bytes = GetBytes("Foo.jpg");

Give the jpeg file a different extension, such as "myfile.jpeg.bin". Visual studio should then treat it as binary file and the generated designer code will return byte[].

Related

How to read a file which build action is marked as embedded/resource?

I have C# project, I added several html files to the solution and marked their action as "resource" or "embedded resource" ("or" -- because I don't see difference when testing).
Now I would like to read them.
When I run this code:
Assembly.GetExecutingAssembly().GetManifestResourceNames()
I get 3 resource names in result:
MyApp.g.resources
MyApp.Properties.Resources.resources
MyApp.Resource.resources
I accessed first, I found desired file name, and I read it this way:
private static byte[] getResource(string name)
{
var assembly = Assembly.GetExecutingAssembly();
string resName = assembly.GetName().Name + ".g.resources";
using (var stream = assembly.GetManifestResourceStream(resName))
{
using (var reader = new System.Resources.ResourceReader(stream))
{
string res_type;
byte[] data;
reader.GetResourceData(name,out res_type,out data);
return data;
}
}
}
As the result I get almost what I wanted -- the content of the file, however with some garbage bytes at the start.
How to do this correctly?
Update: the garbage sequence is -- 6, 0, 0, 239, 187, 191. Three last bytes make BOM.

Why Empty Text File Contains 3 bytes?

I'm using a text file inside my C# project in vs2010. I added to solution and set its "Copy Output" to "Copy Always". When I use the following codes, it gives me the text result with leading three bytes or in utf8 one byte. I looked at windows explorers file properties, its size appears 3 bytes.
public static string ReadFile(string fileName)
{
FileStream fs = null;
try
{
fs = new FileStream(fileName, FileMode.Open);
FileInfo fi = new FileInfo(fileName);
byte[] data = new byte[fi.Length];
fs.Read(data, 0, data.Length);
fs.Close();
fs.Dispose();
string text = Encoding.ASCII.GetString(data);
return text;
}
catch (Exception)
{
if(fs != null)
{
fs.Close();
fs.Dispose();
}
return string.Empty;
}
}
Why is this like above? How can I read text files without StreamReader class?
Any helps, codes wil be very appreciated.
So, those three bytes you are seeing are the byte order marker for the unicode file I am guessing. For UTF-8, it is three bytes.
You can avoid those by saving the file using UTF-8 without signature.

Read Byte Array from a zip file in project folder in WP7

I have a zip file and I have to read its bytes and decrypt. How do I get the byte array from the file which I have added to the project and set its bulid action property as content. Help me.
You can get the bytes of the file this way:
var res = Application.GetResourceStream(new Uri("yourFile", UriKind.Relative));
var fileStream = res.Stream;
byte[] buffer = new byte[fileStream.Length];
fileStream.Read(buffer, 0, (int)fileStream.Length);
Use This.
return File.ReadAllBytes( shapeFileZip.Name );
Its use For C# code.

Zip file with utf-8 file names

In my website i have option to download all images uploaded by users. The problem is in images with hebrew names (i need original name of file). I tried to decode file names but this is not helping. Here is a code :
using ICSharpCode.SharpZipLib.Zip;
Encoding iso = Encoding.GetEncoding("ISO-8859-1");
Encoding utf8 = Encoding.UTF8;
byte[] utfBytes = utf8.GetBytes(file.Name);
byte[] isoBytes = Encoding.Convert(utf8, iso, utfBytes);
string name = iso.GetString(isoBytes);
var entry = new ZipEntry(name + ".jpg");
zipStream.PutNextEntry(entry);
using (var reader = new System.IO.FileStream(file.Name, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
byte[] buffer = new byte[ChunkSize];
int bytesRead;
while ((bytesRead = reader.Read(buffer, 0, buffer.Length)) > 0)
{
byte[] actual = new byte[bytesRead];
Buffer.BlockCopy(buffer, 0, actual, 0, bytesRead);
zipStream.Write(actual, 0, actual.Length);
}
}
After utf-8 encoding i get hebrew file names like this : ??????.jpg
Where is my mistake?
Unicode (UTF-8 is one of the binary encoding) can represent more characters than the other 8-bit encoding. Moreover, you are not doing a proper conversion but a re-interpretation, which means that you get garbage for your filenames. You should really read the article from Joel on Unicode.
...
Now that you've read the article, you should know that in C# string can store unicode data, so you probably don't need to do any conversion of file.Name and can pass this directly to ZipEntry constructor if the library does not contains encoding handling bugs (this is always possible).
Try using
ZipStrings.UseUnicode = true;
It should be a part of the ICSharpCode.SharpZipLib.Zip namespace.
After that you can use something like
var newZipEntry = new ZipEntry($"My ünicödë string.pdf");
and add the entry as normal to the stream. You shouldn't need to do any conversion of the string before that in C#.
You are doing wrong conversion, since strings in C# are already unicode.
What tools do you use to check file names in archive?
By default Windows ZIP implementations use system DOS encoding for file names, while other implementations can use other encoding.

FileUpload to FileStream

I am in process of sending the file along with HttpWebRequest. My file will be from FileUpload UI. Here I need to convert the File Upload to filestream to send the stream along with HttpWebRequest. How do I convert the FileUpload to a filestream?
Since FileUpload.PostedFile.InputStream gives me Stream, I used the following code to convert it to byte array
public static byte[] ReadFully(Stream input)
{
byte[] buffer = new byte[input.Length];
//byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
Might be better to pipe the input stream directly to the output stream:
inputStream.CopyTo(outputStream);
This way, you are not caching the entire file in memory before re-transmission. For example, here is how you would write it to a FileStream:
FileUpload fu; // Get the FileUpload object.
using (FileStream fs = File.OpenWrite("file.dat"))
{
fu.PostedFile.InputStream.CopyTo(fs);
fs.Flush();
}
If you wanted to write it directly to another web request, you could do the following:
FileUpload fu; // Get the FileUpload object for the current connection here.
HttpWebRequest hr; // Set up your outgoing connection here.
using (Stream s = hr.GetRequestStream())
{
fu.PostedFile.InputStream.CopyTo(s);
s.Flush();
}
That will be more efficient, as you will be directly streaming the input file to the destination host, without first caching in memory or on disk.
You can't convert a FileUpload into a FileStream. You can, however, get a MemoryStream from that FileUpload's PostedFile property. You can then use that MemoryStream to fill your HttpWebRequest.
You can put a FileUpload file directly into a MemoryStream by using FileBytes (simplified answer from Tech Jerk)
using (MemoryStream ms = new MemoryStream(FileUpload1.FileBytes))
{
//do stuff
}
Or if you do not need a memoryStream
byte[] bin = FileUpload1.FileBytes;

Categories