I'm currently using the below C# code to create my Lexparser with success:
return LexicalizedParser.loadModel(projectDir + #"StanfordResources/lexparser/englishPCFG.ser.gz");
But due to deployment reasons I would rather embed the 'englishPCFG.ser.gz' file as some sort of resource either into the assembly or as a Resource.resx.
So I try to read my byte[] file as so:
ObjectInputStream stream = new ObjectInputStream(new ByteArrayInputStream(Resource.englishPCFG_ser));
return LexicalizedParser.loadModel(stream);
But I get the below error:
java.io.StreamCorruptedException: invalid stream header: 1F8B0800
Is there another way to load this rather than from a file path or am I doing a silly?
1F8B0800 is the GZIP header, which makes sense, given the name of the file you're trying to read. So you need to put java.util.zip.GZIPInputStream between the ByteArrayInputStream and ObjectInputStream:
new ObjectInputStream(new GZIPInputStream(new ByteArrayInputStream(Resource.englishPCFG_ser)))
Related
I need to send an image as a Byte Array to facebook API. I try to get the file from my Mac and send it but it is breaking in second line when it is reading file.
string fileName = Path.GetFileName(request.PhotoUrl);
byte[] photoContent = File.ReadAllBytes(fileName);
I am using Mac, so my path is looks like:
"photoUrl": "/Users/myname/Documents/test.png"
It is bringing fileName is but braking in second line.
Path.GetFileName() should be returning the filename and its extension. So in your case, fileName will be set to test.png Therefore when you try to read the file your call to File.ReadAllBytes(fileName) will fail unless you are running the program from the same folder as the picture file. Instead of using Path.GetFileName() you could use Path.GetFullPath() or even just pass the PhotoUrl value to the ReadAllBytes function.
Microsoft documentation for
GetFullPath(): https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getfullpath?view=netcore-3.1
GetFileName(): https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getfilename?view=netcore-3.1
So, I have been running into all kinds of CORS errors (when using HTTPS) and Not allowed to load local resource: file:///C:/Windows/TEMP/e3ef26_75603_4.xml when saving my file to a temp folder and then trying to serve the request via AJAX to be displayed on my browser.
Basically the scenario is that I am requesting a file from a S3 bucket. Now there are couple of things that I tried:
By directly giving the full file path (HTTPS) with associated bucket and file name to a AJAX call. This is done by first generating the file path on the Controller method and assigning a ViewBag variable. Something like:
ViewBag.currentURL = JsonConvert.SerializeObject(tempfilepath);
And associated AJAX:
$(function executeXML() {
//console.log('#Html.Raw(ViewBag.currentURL)');
$("#myeditor").execute({
ajaxOptions: {
pathtoxml: #Html.Raw(ViewBag.currentURL)
},
});
});
This method works quite well when the S3 bucket has public access and the CORS policies are there for the bucket.
Problem: Using this method on a S3 bucket that has no public access and no CORS policies will result in the No 'Access-Control-Allow-Origin' header is present on the requested resource from any browser.
Sigh! But not yet,
The second method that I was trying to do is to read the file on the server side and save it to a XML document. Now when I want to save this XML document, I use a temp folder to save my file. Something like this:
using (WebClient client = new WebClient())
{
string myXMLString = client.DownloadString(fullpathstory);
XmlDocument xml = new XmlDocument();
xml.LoadXml(myXMLString); // suppose that myXmlString contains "<Names>...</Names>"
//Now save the file to temp folder
tempfilepath = Path.Combine(Path.GetTempPath(), filename);
xml.Save(tempfilepath);
}
This gives me a path like: file:///C:/Windows/TEMP/e3ef26_75603_4.xml
Now when I am sending this path to my AJAX, it gives me the error jquery.min.js:4 Not allowed to load local resource: file:///C:/Windows/TEMP/e3ef26_75603_4.xml which is quite obvious and expected.
Question: I am looking for a way to save my XML document in-memory and generate a path or a stream that can be read by my AJAX call and serve it on the browser.
Is there such a way or do I need to create a proper file sever where I store all my generated XML files and then read from that location. It would basically be a temp server folder but then I would need to keep monitoring the ever increasing size of it.
Thanks in advance
Rather than pre generating the file, i would recommend to generate file on demand. The moment user issues an ajax request for file, file would be generated in memory, converted to byte array, returned to client (as a base64 encoded string) and download would start at client's end.
I'm downloading in image from web to save it locally. It works great with any other image formats but it this method below fails with an argument exception when I try to read a WebP image.
private static Image GetImage(string url)
{
try
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
return Image.FromStream(response.GetResponseStream());
}
catch
{
return null;
}
}
How do you read .webp images in C#?
I found this other question that allows for converting between types but I do not want to do that WebP library for C#
Reason I'm not wanting to do it is because I think it might lose some quality. Besides, I want to know why is this not working.
The base class libraries won't help you to deal with WebP images. However, if you only want to save the received file to the disk, you don't have to even know that you are dealing with a WebP images. You can simply treat the received data as a binary blob and dump it to a file, for example using Stream.CopyTo and a FileStream.
The Content-Type HTTP header will give you the mime type of the file you're downloading, and the Content-Disposition header can provide you with a filename and extension (though you might have to do some parsing). You can access those using HttpWebResponse.ContentType and HttpWebResponse.Headers["Content-Disposition"].
#Trillian nailed it. Here is a code snippet for what I did based on his suggestion. Wanted to add code so not posting this as a comment.
To get just the image file extension, you can do this
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string fileExt = response.ContentType.Replace("image/", string.Empty);
To get the file name with extension, you can do the following and the do parsing like I did above. It just has some more data in it.
response.Headers["Content-Disposition"];
Once you have you file name you want to save as, create a file stream and copy the response stream into it.
FileStream fs = new FileStream(targetPath + fileName, FileMode.Create);
response.GetResponseStream().CopyTo(fs);
Assuming you app has access to the destination, image should get saved. Make sure to add try catch and handle exceptions properly. Also note that FileMode.Create will overwrite if the file already exists!
I have the following file:
C:\Users\Jan\Documents\Visual Studio 2010\Projects\AzureTests\Build\82df3c44-0482-47a7-a5d8-9b39a79cf359.cskpg\WebRole1_778722b2-eb95-476d-af6a-917f269a0814.cssx\39e5cb39-cd18-4e1a-9c25-72bd1ad41b49.csman
I can open this file fine via the open window in notepad++, or via the explorer. However, opening via the Run window doesn't work. It gives an 'cannot find the file' dialog. When I query the filesystem in C# with:
var dir = new DirectoryInfo(#"C:\Users\Jan\...")
var fil = dir.GetFiles("*.csman")[0];
The file is also in the list of returned files but I can't do a:
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(fil.FullName);
Because this fails with an 'incorrect data at (1,1)' error. Because the XmlDocument thinks the file is empty. However a File.ReadAllBytes on this file succeeds. This works:
var buf = File.ReadAllBytes(fil.FullName);
using (var ms = new MemoryStream())
{
ms.Write(buf, 0, (int) buf.Length);
ms.Seek(0, SeekOrigin.Begin);
xmlDoc.Load(ms);
}
The problem doesn't occur when calling...
xmlDoc.Save(fil.FullName);
Can someone explain what is happening here?
XmlDocument.LoadXml expects a string that directly contains the XML data.
Parameters
xml
Type: System.String
String containing the XML document to load.
It is therefore interpreting the path-string as if it were XML (which will obviously be invalid, which is why the exception is thrown).
Use the XmlDocument.Load method instead.
Parameters
filename
Type: System.String
URL for the file containing the XML document to load. The URL can be either a local file or an HTTP URL (a Web address).
You don't face the problem when calling XmlDocument.Save, because, like Load, it's single parameter represents the path to the file.
Basically, the somewhat long file-path you've got there is a red-herring and not the root-cause of the issue you are facing.
And your other problem:
Windows "Run" requires quotes around the path name if there are spaces in it.
Okay so I want to download a file from a website, but the file is lacking an extension.
(it's an image file, I know this much, but the link does not provide the actual extension)
When I use webrequest, or webclient to download the file I get a "404 file not found" exception.
WebClient wc = new WebClient();
Stream strm = wc.DownloadFile("http://some_site.some_domain/some_image.","C:/some_directory/save_name.some_extention");
Notice the lack of extention at the end of the URL.
The site in question displays the image fine in a webbrowser, but when viewing just the image there is no extension and thus it's treated an unknown file (not showing an image).
So simply put: how do I download a file if there is no extention specified?
Thanks in advance!
So you're trying to determine what extension to give the file after downloading? If the URL doesn't have one you would have to inspect the actual data of the file.
You might be able to inspect the beginning of the file and see if it matches known valid file types. For instance, PNGs seem to have 'PNG' as bytes 2-4 (at least in the ones I've inspected). By looking at that data you should be able to determine the format with a fairly high accuracy.
This would be my best suggestion, if this doesn't work I don't know how to solve you problem...
List<string> fileExtensions = new List<string>(){"png","gif","bmp","jpg"}// other known image file extensions here...
WebClient wc = new WebClient();
foreach(var extension in fileExtensions)
{
try
{ wc.DownloadFile("http://some_site.some_domain/some_image."+extension,"C:/some_directory/save_name."+extension);
break;
}
catch {}
}
This would just be a work around, I guess... Not a real solution...