I have written a patcher for my game but I am stuck at the actual saving of the files part. I keep on getting the following error from unity:
System.ArgumentException: Name has invalid chars
at System.IO.FileStream..ctor....
Here is the code that is in charge of saving my files:
function downloadFile(file:String){
var download:WWW = WWW(rawDataFolder+""+file); //download file from platforms raw folder
yield download; // wait for download to finish
// var saveLoc = Application.persistentDataPath; //Location where the files will go
var saveLoc = "C:\\games";
try{
Debug.Log(saveLoc+"\\"+file);
File.WriteAllBytes (saveLoc+"\\"+file+".FILE", download.bytes); //<----PROBLEM HERE.
}
catch(error){
updateMsg ="Update Failed with error message:\n\n"+error.ToString();
errorOccured = true;
Debug.Log(error);
}
}
I am trying to download a file called "level0". It doesn't have a file extension... in windows explorer it says it is simply 'FILE'. So I was thinking it was a binary file. Am I wrong? What might be causing my null character problem? This missing extension? Any help on this would be amazing.
I found out that my problem originated in the text file that I was reading. The text file must have had spaces in it. Using the ".Trim()" command I was able to remove the invalid char error. Once that was removed it worked perfectly reading files without extensions (Binary Files).
Related
I have proper .dotm template.
When I create a new file based on a template by double clicking in explorer it creates the correct file (based on this template). Created file size after save is 16Kb (without any content).
But if I want to use .CreateFromTemplate method in my code I cannot open a newly created .docx file in MS Word.
New file size is 207Kb (just like .dotm file). MS Word display "run-time error 5398" and not open the file.
I'm using nuget package DocumentFormat.OpenXml 2.19.0, Word 365 version 16.0.14931.20648 - 32bit and code like this:
using (WordprocessingDocument doc = WordprocessingDocument.CreateFromTemplate(templatePath))
{
doc.SaveAs(newFileName);
}
Google is silent about this error, ChatGPT says that:
The "Run-time Error 5398" error means that the file you are trying to open is corrupted or not a valid docx file. Possible reasons for this error may be the following:
The file was not saved correctly after making changes. Verify that the Save() method was called after making changes to the file.
The file was saved with the wrong extension, e.g. as DOTM instead of DOCX
The file was saved in an invalid format.
There may have been some unhandled exceptions in your code.
When I manually change the extension of a new file from docx to dotm, there is no error when opening, but the file does not open.
What am I doing wrong with CreateFromTemplate method?
I tried to reproduce the behavior you described, using the following unit tests:
public sealed class CreateFromTemplateTests
{
private readonly ITestOutputHelper _output;
public CreateFromTemplateTests(ITestOutputHelper output)
{
_output = output;
}
[Theory]
[InlineData("c:\\temp\\MacroEnabledTemplate.dotm", "c:\\temp\\MacroEnabledDocument.docm")]
[InlineData("c:\\temp\\Template.dotx", "c:\\temp\\Document.docx")]
public void CanCreateDocmFromDotm(string templatePath, string documentPath)
{
// Let's not attach the template, which is done by default. If a template is attached, the validator complains as follows:
// The element has unexpected child element 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:attachedTemplate'.
using (var wordDocument = WordprocessingDocument.CreateFromTemplate(templatePath, false))
{
// Validate the document as created with CreateFromTemplate.
ValidateOpenXmlPackage(wordDocument);
// Save that document to disk so we can open it with Word, for example.
wordDocument.SaveAs(documentPath).Dispose();
}
using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(documentPath, true))
{
// Validate the document that was opened from disk, just to see what Word would open.
ValidateOpenXmlPackage(wordDocument);
}
}
private void ValidateOpenXmlPackage(OpenXmlPackage openXmlPackage)
{
OpenXmlValidator validator = new(FileFormatVersions.Office2019);
List<ValidationErrorInfo> validationErrors = validator.Validate(openXmlPackage).ToList();
foreach (ValidationErrorInfo validationError in validationErrors)
{
_output.WriteLine(validationError.Description);
}
if (validationErrors.Any())
{
// Note that Word will most often be able to open the document even if there are validation errors.
throw new Exception("The validator found validation errors.");
}
}
}
In both tests, the documents are created without an issue. Looking at the Open XML markup, both documents look fine. However, while I don't get any runtime error, Word also does not open the macro-enabled document.
I am not sure why that happens. It might be related to your security settings.
Depending on whether or not you really need to use CreateFromTemplate(), you could create a .docm (rather than a .dotm) and create new macro-enabled documents by copying that .docm.
I opened an issue in the Open XML SDK project on GitHub.
I have created a taskpane addin for word that is using the Document.getFileAsync method to get the document contents in Compressed format (docx).
This works correctly for .docx files, but unsurprisingly fails if an old .doc file is used.
I get the following error:
code: 5001
message: "An internal error has occurred."
name: "Internal Error"
Is there a way to detect documents in invalid formats before calling getFileAsync?
I have tried reading the document properties format value using the following code:
return Word.run(function (context) {
var properties = context.document.properties;
context.load(properties, "format");
return context.sync()
.then(function () {
return properties.format;
});
});
But the returned value is always an empty string for both docx and doc files.
I would like to be able to detect old file formats so that I can display an appropriate error message to the users.
getFileAsync() method works for .docx file only. Just to detect the correct file you can simply check the extension of the file: fname.substr((~-fname.lastIndexOf('.') >>> 0) + 2) where fname is filename here. And prompt your message accordingly.
I am getting the following exception in my glassfish 4 application that uses log4j2:
SEVERE: ERROR StatusLogger Invalid URL C:/glassfish4/glassfish/domains/domain1/config/log4j2.xml java.net.MalformedURLException: Unknown protocol: c
I have the following section in my log4j2.xml:
<RollingFile name="RollingFile" fileName="C:/glassfish4/glassfish/domains/domain1/logs/ucsvc.log"
filePattern="C:/glassfish4/glassfish/domains/domain1/logs/$${date:yyyy-MM}/ucsvc-%d{MM-dd-yyyy}-%i.log">
I understand that if it's looking for a URL, then "C:/glassfish4/..." is not the correct format.
However, the rolling file part actually works: I see a log file and the rolled log files where I expect them.
If I change to a URL (e.g. file:///C/glassfish4/...) that doesn't work at all.
So should I ignore the exception? (everything seems to be working ok). Or can someone explain the correct format for this section of the configuration?
I have not yet fully determined why it is that the config file works for me as well as the OP, but, I can confirm that changing the path reference to a file:// url solves the problem (ie: gets rid of the error/warning/irritant).
In my IntelliJ Run/Debug configurations, for VM options, I have:
-Dlog4j.configurationFile=file://C:\dev\path\to\log4j2.xml
I can confirm that '\' are translated to '/' so, no worries there.
EDIT:
Okay, the whole thing works because they (the apache guys) try really hard to load the configuration and they do, in fact, load from the file as specified via the c:\... notation. They just throw up a rather misleading exception before continuing to try.
In ConfigurationFactory::getConfiguration:
**source = getInputFromURI(FileUtils.getCorrectedFilePathUri(config));**
} catch (Exception ex) {
// Ignore the error and try as a String.
}
if (source == null) {
final ClassLoader loader = this.getClass().getClassLoader();
**source = getInputFromString(config, loader);**
The first bolded line tries to load from a URL and fails, throwing the exception. The code then continues, pops into getInputFromString:
try {
final URL url = new URL(config);
return new ConfigurationSource(url.openStream(), FileUtils.fileFromURI(url.toURI()));
} catch (final Exception ex) {
final ConfigurationSource source = getInputFromResource(config, loader);
if (source == null) {
try {
**final File file = new File(config);
return new ConfigurationSource(new FileInputStream(file), file);**
Where it tries to load the config again, fails and falls into the catch, tries again, fails and finally succeeds on the bolded lines (dealing with a File).
Okay, the code lines I wanted in emphasize with bold are actually just wrapped in **; guess the site doesn't permit nested tags? Anyway, y'all get the meaning.
It's all a bit of a mess to read, but that's why it works even though you get that nasty-looking (and wholly misleading) exception.
Thanks Jon, i was searching all over.. this helped!
This is on Intellij 13, Tomcat 7.0.56
-Dlog4j.configurationFile=file://C:\Surendra\workspace\cmdb\resources\elasticityLogging.xml
The problem is not the contents of your log4j2.xml file.
The problem is that log4j2 cannot locate your log4j2.xml config file. If you look carefully at the error, the URL that is reported as invalid is C:/glassfish4/glassfish/domains/domain1/config/log4j2.xml: the config file.
I'm not sure why this is. Are you specifying the location of the config file via the system property -Dlog4j.configurationFile=path/to/log4j2.xml?
Still, if the application and logging works then perhaps there is no problem. Strange though. You can get more details about the log4j configuration by configuring <Configuration status="trace"> at the top of your log4j2.xml file. This will print log4j initialization details to the console.
This is a weird one... I have a CSV file on the server and make it available to users via the code below. Typically, the results set is correct, except that it always omits the last field of the last record:
Co Name,Process Date,Employee Id,Last Name,First Name,Cust Auth,ENTERED_HRS,Labor Type
Temp,2014-02-21,CONTRACTOR0001,Dahlenburg,Eric,131137057134,5,0
Temp,2014-02-21,CONTRACTOR0001,Dahlenburg,Eric,1411310002,8,0
Temp,2014-02-21,CONTRACTOR0001,Dahlenburg,Eric,1411320015,6.69,0
Temp,2014-02-21,CONTRACTOR0001,Dahlenburg,Eric,1413500001105,6
Notice there is no ",0" at the end of the last record? In Visual Studios, it works fine, but on my development server, it omits that last part.
I verified that the source CSV file has all the data fields. I tried different path locations for the CSV file, but no change. Can't understand why it works on Visual Studios and not on the server.
addendum: I don't know if it matters, but the source file is located on a virtual directory(not physical) on the server. Any Ideas???
// Causes Save As Dialog box to appear for user.
String FileName = fileName;
String FilePath = strFilePath;
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/csv";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.WriteFile(FilePath + FileName);
response.Flush();
response.Close();
// response.End(); // Same as response.TransmitFile(), but causes an exception because it raises the EndRequest event.
After a lot of trial and error, I found that I can get it to work if I use the Content type:
response.ContentType = "application/csv";
Not sure why this is different from text/csv, but its working now.
Also, You could use
response.ContentType = "application/vnd.ms-excel";
As well, but its going to prompt the user that the file is not in the proper format, do you want
to open anyway.
Eric
I'm currently trying to load a PDF document using the Zend_Pdf::load($filename) method and I'm getting
Error occured while 'xxx.pdf' file reading.
So I see in Zend_Pdf_Parser::_construct there is this block
while ($byteCount > 0 && !feof($pdfFile)) {
$nextBlock = fread($pdfFile, $byteCount);
if ($nextBlock === false) {
require_once 'Zend/Pdf/Exception.php';
throw new Zend_Pdf_Exception( "Error occured while '$source' file reading." );
}
$data .= $nextBlock;
$byteCount -= strlen($nextBlock);
}
if ($byteCount != 0) {
require_once 'Zend/Pdf/Exception.php';
throw new Zend_Pdf_Exception( "Error occured while '$source' file reading." );
}
After debugging, I can tell that strlen($nextBlock) is not returning the right value (based on $nextBlock = fread($pdfFile, $byteCount); )
If I use mb_strlen($nextBlock,'8bit') instead this block passes right. Now I'm getting another error
Pdf file syntax error. 'startxref' keyword expected
So now I look into Zend_Pdf_StringParser:readLexeme() and I can see that again there is a problem with singlebyte vs. multibyte string functions (strlen etc.)
So does anybody have a clue what's going on with Zend_Pdf, if this is general bug or I'm just missing something?
I never used Zend_PDF because it has very few potential. I advise you to integrate into your project TCPDF! ;)
I experienced the same error and it turned out to be a bug in Zend Guard. Apparently my version of the PHP encoder turns the ASCII NP form feed character (\f) inside string literals into the backslash (\) and the f characters (\\f).
The obfuscated version of
print bin2hex("\f");
outputs
5c66
instead of the expected
0c
This behavior causes Zend_Pdf_StringParser to parse 'startxre' instead of 'startxref' in readLexeme, causing the error you described.
If you are using a different version of the encoder or no encoder at all, then this may not be the cause of the problem (try reproducing it on a different PHP version).