XmlDocument loading from file with non latin file path - c#

I have instantiated XmlDocument and than trying to load XML file with non Latin symbols in the file pat. During loading the file I am facing with the
ArgumentNullException
with message:
"Value cannot be null. Parameter name: str"
Stack Trace is -
at System.Security.Permissions.FileIOPermission.HasIllegalCharacters(String[] str)
at System.Security.Permissions.FileIOPermission.AddPathList(FileIOPermissionAccess access, AccessControlActions control, String[] pathListOrig, Boolean checkForDuplicates, Boolean needFullPath, Boolean copyPathList)
at System.Security.Permissions.FileIOPermission..ctor(FileIOPermissionAccess access, String path)
at System.Uri.ParseConfigFile(String file, IdnScopeFromConfig& idnStateConfig, IriParsingFromConfig& iriParsingConfig)
at System.Uri.GetConfig(UriIdnScope& idnScope, Boolean& iriParsing)
at System.Uri.InitializeUriConfig()
at System.Uri.InitializeUri(ParsingError err, UriKind uriKind, UriFormatException& e)
at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
at System.Uri..ctor(String uriString, UriKind uriKind)
at System.Xml.XmlResolver.ResolveUri(Uri baseUri, String relativeUri)
at System.Xml.XmlUrlResolver.ResolveUri(Uri baseUri, String relativeUri)
at System.Xml.XmlTextReaderImpl..ctor(String url, XmlNameTable nt)
at System.Xml.XmlTextReader..ctor(String url, XmlNameTable nt)
at System.Xml.XmlDocument.Load(String filename)
at ....
There is a part of my code:
var xmlData = new XmlDocument();
if (File.Exists(xmlPath))
{
xmlData.Load(xmlPath);
...
}
xmlPath contain French letters.
What is wrong?
How I can open xml file with non latin characters?

Load the file path into a uri first:
Uri xmlUri = new Uri(xmlPath);
xmlData.Load(xmlUri.AbsolutePath);

I have found solution of the problem with using other class for data loading, like this:
var d = File.ReadAllText(xmlPath);
xmlData.LoadXml(d);
But question - "what is wrong?" still open.

Related

How to resolve Invalid Uri Exception in Excel?

I am using OfficeOpenXml for reading the excel file in C#. But when I am trying to open and reading some sheet from it, it's throwing exception as below:
at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
at System.Uri..ctor(String uriString, UriKind uriKind)
at MS.Internal.IO.Packaging.InternalRelationshipCollection.ProcessRelationshipAttributes(XmlCompatibilityReader reader)
at MS.Internal.IO.Packaging.InternalRelationshipCollection.ParseRelationshipPart(PackagePart part)
at MS.Internal.IO.Packaging.InternalRelationshipCollection..ctor(Package package, PackagePart part)
at System.IO.Packaging.PackagePart.EnsureRelationships()
at System.IO.Packaging.PackagePart.GetRelationshipHelper(String id)
at System.IO.Packaging.PackagePart.GetRelationship(String id)
at OfficeOpenXml.ExcelWorkbook.GetExternalReferences()
at OfficeOpenXml.ExcelPackage.get_Workbook()
at ServiceHandlerUNIC.UploadTuningFile() in d:\Srusti\Projects\WECSWebConfigurator\07_SourceCode\WECSWebConfigurator\App_Code\ServiceHandlerUNIC.cs:line 56392
How can I identify this thing? Because it's working with one excel file while another excel file is throwing an error. My code is :
ExcelPackage ep = new ExcelPackage(new FileInfo(fileFUllPath));
ExcelWorksheet ws = ep.Workbook.Worksheets["Configuration"];

FileStream will not open Win32 devices such as disk partitions and tape drives. (DotNetZip)

I'm trying to use DotNetZip to handle zip files, but whenever I try to open a file I get the following error:
[SEVERE] System.ArgumentException: FileStream will not open Win32 devices such as disk partitions and tape drives. Avoid use of "\\.\" in the path.
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode)
at Ionic.Zip.ZipEntry.InternalExtract(String baseDir, Stream outstream, String password)
at Ionic.Zip.ZipEntry.Extract(String baseDirectory)
at Ionic.Zip.ZipFile._InternalExtractAll(String path, Boolean overrideExtractExistingProperty)
at Ionic.Zip.ZipFile.ExtractAll(String path)
at ModsInstaller.Form1.MergeDirectories(String Path1, String Path2) in C:\Users\Admin\documents\visual studio 2010\Projects\ModsInstaller\ModsInstaller\Form1.cs:line 275
at ModsInstaller.Form1.CustomInstallForge() in C:\Users\Admin\documents\visual studio 2010\Projects\ModsInstaller\ModsInstaller\Form1.cs:line 259
at ModsInstaller.Form1.btn_install_Click(Object sender, EventArgs e) in C:\Users\Admin\documents\visual studio 2010\Projects\ModsInstaller\ModsInstaller\Form1.cs:line 120
and here's the code:
private void MergeDirectories(string Path1, string Path2)
{
string outDirectory = Path.GetFullPath(workspace + "\\temp\\dir");
if (!Directory.Exists(outDirectory))
Directory.CreateDirectory(outDirectory);
Path1 = Path.GetFullPath(Path1);
Path2 = Path.GetFullPath(Path2);
Log("Extracting {0} to temp dir.", Path1);
using (ZipFile zip = ZipFile.Read(Path1))
{
zip.ExtractAll(outDirectory); //this line throws the error
}
Log("Extraction sucessfull");
Log("Extracted {0} to temp dir.", Path2);
ZipFile.Read(Path2).ExtractAll(Path.GetFullPath(workspace + "\\temp\\dir"));
Log("Extraction sucessfull");
ZipFile z = new ZipFile(workspace + "\\temp\\build.jar");
z.AddDirectory(workspace + "\\temp\\dir");
z.Save();
z.Dispose();
}
and when I insert a breakpoint I see that:
outDirectory = "C:\\Users\\Admin\\documents\\visual studio 2010\\Projects\\ModsInstaller\\ModsInstaller\\bin\\Debug\\temp\\dir"
Can anyone point out what I'm doing wrong?
Thanks.
I had the same error with CON file name. It is not because of Ionic.Zip lib., but rather due to the Windows file naming convention.
Check the content of the first ZIP file if it has some unusual file names.
For example, in Windows you cannot create file with name CON, AUX, NUL, COM1, etc.
You can read more about it in reserved names section:
https://learn.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#file_and_directory_names
Solution to it is to take other zip file for testing or extract it under unix system or ask file provider to send vulnerable file(s) with differentia file name or at least lower case.
Usage
MergeDirectories("Sample 1.zip", "Sample 2.zip", "Merged.zip");
Code:
private void MergeDirectories(string filePath1, string filePath2, string mergedName)
{
string workspace = Environment.CurrentDirectory;
filePath1 = Path.Combine(workspace, filePath1);
filePath2 = Path.Combine(workspace, filePath2);
mergedName = Path.Combine(workspace, mergedName);
if (File.Exists(mergedName))
{
File.Delete(mergedName);
}
DirectoryInfo zip1 = OpenAndExtract(filePath1);
DirectoryInfo zip2 = OpenAndExtract(filePath2);
string merged = Path.GetTempFileName();
using (ZipFile z = new ZipFile())
{
z.AddDirectory(zip1.FullName);
z.AddDirectory(zip2.FullName);
z.Save(merged);
}
zip1.Delete(true);
zip2.Delete(true);
File.Move(merged, mergedName);
}
private DirectoryInfo OpenAndExtract(string path)
{
string tmpName = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
string tmp = Path.Combine(Path.GetTempPath(), tmpName);
FileInfo sourcePath = new FileInfo(path);
DirectoryInfo tempPath = Directory.CreateDirectory(tmp);
using (ZipFile zip = ZipFile.Read(sourcePath.FullName))
{
zip.ExtractAll(tempPath.FullName);
}
return tempPath;
}

RAD PDF Service Message Worker Thread Unknown Exception

I try to open My PDF through RadPdf control but i get rendering error . i check the event viewer and get the following data :
to fix the problem i have to create C:\WINDOWS\TEMP\RadPdfTemp\ and the admin every period of time empty the temp and this folder removed , i try to create this folder in my my web site with the required permissions but still get the same error !!!
this.rad_pdf.CreateDocument("Document Name", pdfData);
I get pdfData through :
private byte[] AddReportToResponse(LocalReport followsReport)
{
string mimeType;
string encoding;
string extension;
string[] streams = new string[100];
Warning[] warnings = new Warning[100];
byte[] pdfStream = followsReport.Render("PDF", "", out mimeType, out encoding, out extension, out streams, out warnings);
return pdfStream;
}
Event Type: Error
Event Source: RAD PDF
Event Category: None
Event ID: 0
Date: 4/21/2013
Time: 2:33:50 PM
User: N/A
Computer: -----
Description:
Event Category
-----------------
PdfService
Event Description
-----------------
RAD PDF Service Message Worker Thread Unknown Exception
Exception Type:
System.IO.DirectoryNotFoundException
Exception Message:
Could not find a part of the path 'C:\WINDOWS\TEMP\RadPdfTemp\p476.tmp'.
Exception Stack Trace:
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
at System.IO.File.WriteAllBytes(String path, Byte[] bytes)
at #Ew.#Rw.#ix()
at #Ew.#Rw.#9w()
Event User
-----------------
NT AUTHORITY\SYSTEM
Event Version
-----------------
2.12.0.0
For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.
You should check if the temp folder exist otherwise create it before you open the PDF file. That will make sure the folder is there and no exception is thrown.
string tempDirectory = Path.Combine(Path.GetTempPath(), "RadPdfTemp");
if (!Directory.Exists(tempDirectory))
Directory.CreateDirectory(tempDirectory);
this.rad_pdf.CreateDocument("Document Name", pdfData);

Exception: Access Denied when using FileStream

The following line is throwing an exception. I have no idea why.
using (var output = new FileStream(sftpFile.Name, FileMode.Create,FileAccess.ReadWrite))
Exception is:
Error: System.UnauthorizedAccessException: Access to the path 'C:\Users\roberth\
Programming_Projects\Common\UI\bin\Debug' is denied.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access,
Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions
options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy,
Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access)
at CWD.Networking.DownloadFromSftp(String hostname, String user, String passw
ord, Int32 port, String localPath, String remotePath, String filename) in c:\Use
rs\roberth\Programming_Projects\Common\Common\Common.cs:line 566
Line 566 is the using statement above.
Can anyone shed some light as to why I may be triggering an error? I have full permissions to the directory, no compilation issues, I can create new files and folders manually in that directory as well.
--Edit--
I tried running VS as administrator as suggested with no resolution.
The UnauthorizedAccessException error message tells you what file it is you're trying to open:
C:\Users\roberth\Programming_Projects\Common\UI\bin\Debug
This looks like a directory name: you can't open a directory as a file.
You've presumably forgotten to append a filename:
string filename = Path.Combine(sftpFile.Name, "SomeFile.dat");
using (var output = new FileStream(filename,...)
{
...
}
You need to use something similar to the following:
private bool EnviarArchivoSFTP(string PuertoSFTP, string UrlFTP, string CarpetaFTP, string UsuarioFTP, string PasswordFTP, string FicheroFTP, string nombreArchivo)
{
bool archivoEnviado = false;
using (var client = new SftpClient(UrlFTP, int.Parse(PuertoSFTP), UsuarioFTP, PasswordFTP))
{
client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(1);
client.OperationTimeout = TimeSpan.FromSeconds(1);
client.Connect();
client.ChangeDirectory(CarpetaFTP);
string dataPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
string appFile = Path.Combine(dataPath, FicheroFTP, nombreArchivo);//Se brindan permisos full sobre la carpeta
using (var fileStream = new FileStream(appFile, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
client.BufferSize = 4 * 1024; // bypass Payload error large files
client.UploadFile(fileStream, Path.GetFileName(nombreArchivo));
archivoEnviado = true;
}
}
return archivoEnviado;
}

how can i format the file name like it includes date and time and month and year

At the moment I am using to store the zip files with the file name like this...
backup-20111010092345.Zip
but i want to change the file name to this ..backup-2011-10-10_09:23:45.Zip
i have got this code ...
string zipName = Path.Combine(filepath, string.Format("backup-{0}.zip", DateTime.Now.ToString("yyyyMMddhhmmss")));
string backupFilePath = Path.Combine(filepath, backupName);
using (ZipFile zip = new ZipFile())
{
zip.AddFile(backupFilePath, "");
zip.Save(zipName);
}
string backupName = "backup.sql";
string filepath = #"C:\Folder\Back\";
would any one pls help on this...
many thanks In advance...
Modified Code:
string zipName = Path.Combine(filepath, string.Format("backup-{0:yyyy-MM-dd_HH:mm:ss}.zip", DateTime.Now));
string backupFilePath = Path.Combine(filepath, backupName);
using (ZipFile zip = new ZipFile())
{
zip.AddFile(backupFilePath, "");
zip.Save(zipName);
}
Error :Notsupported Exception was unhandled
this is stack trace .
at System.Security.Util.StringExpressionSet.CanonicalizePath(String path, Boolean needFullPath)
at System.Security.Util.StringExpressionSet.CreateListFromExpressions(String[] str, Boolean needFullPath)
at System.Security.Permissions.FileIOPermission.AddPathList(FileIOPermissionAccess access, AccessControlActions control, String[] pathListOrig, Boolean checkForDuplicates, Boolean needFullPath, Boolean copyPathList)
at System.Security.Permissions.FileIOPermission..ctor(FileIOPermissionAccess access, String[] pathList, Boolean checkForDuplicates, Boolean needFullPath)
at System.IO.File.Move(String sourceFileName, String destFileName)
at Ionic.Zip.ZipFile.Save()
at Ionic.Zip.ZipFile.Save(String fileName)
error: The given path's format is not supported.
Sounds like you've nearly got it (in terms of building the name that you specified) - you just need to change the format string
string zipName = Path.Combine(filepath,
string.Format("backup-{0}.zip",
DateTime.Now.ToString("yyyy-MM-dd_HH:mm:ss"));
You could specify that as:
string zipName = Path.Combine(filepath,
string.Format("backup-{0:yyyy-MM-dd_HH:mm:ss}.zip",
DateTime.Now));
It's up to you which you find more readable.
Note that this will use the time separator for the current culture. If you always want it to be "colon" then you should quote it. On the other hand, is colon even a valid character in Windows filenames? Consider using dash again, or something similar. For example:
string zipName = Path.Combine(filepath,
string.Format("backup-{0:yyyy-MM-dd_HH-mm-ss}.zip",
DateTime.Now));
You'll need to use something other than : as it is reserved. I suggest something like:
DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss");
As well as the build in formats, you can get the individual components of a DateTime object using its properties like myDate.Year etc. These are detailed on MSDN here:
http://msdn.microsoft.com/en-us/library/991wfdee(v=VS.90).aspx
So if you wanted some really odd formatting you could put together a composite string from each component part in whatever pattern you want.

Categories

Resources