Consider the following code snippet
private void ProcessFile(string fullPath) {
XmlTextReader rdr = new XmlTextReader("file:\\\\" + fullPath);
while (rdr.Read()) {
//Do something
}
return;
}
Now, this functions fine when passed a path like:
"C:\Work Files\Technical Information\Dummy.xml"
But throws an error when passed
"C:\Work Files\#Technical Information\Dummy.xml"
Note that all folders and files specified exist and that the hash character is a valid character for paths. The error details are:
System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Work Files\'.
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, Int32 bufferSize)
at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials)
at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn)
at System.Xml.XmlTextReaderImpl.OpenUrlDelegate(Object xmlResolver)
at System.Threading.CompressedStack.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.CompressedStack.Run(CompressedStack compressedStack, ContextCallback callback, Object state)
at System.Xml.XmlTextReaderImpl.OpenUrl()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.XmlTextReader.Read()
Anybody know what's going on?
Adding to Konrad's answer, if you are using the file:// protocol, you need to use %23 for # then it works fine
Try omitting the file:/// protocol prefix. It works for me without one. I believe .NET will truncate any part after the # if it believes this to be a URL. This is only a guess based on the error message but it seems logical considering that the part after the # character isn't processed by the server but rather by the client in other scenarios (e.g. web browsers).
Why don't you use
XmlTextReader rdr = new XmlTextReader(fullPath);
Related
Background
I currently have a usb device which has all my projects which I am working on and it stays in my office's docking station. Last night I was bored and wanted to continue work on a project, However no files? This made me think about writing a console app that would copy all the files from my usb drive to a folder on my desktop and would run as a scheduled task at a certain hour.
Problem
I am trying to use a System.IO.Compression.FileSystem in order to compress the file in order in order to then move it to a new directory on my PC. The documentation gives an example here ZipFile class. IT seems very up front. However, when I am trying to copy it to a new destination I get the following error.
Error
Message
Access to the path 'C:\Users\er4505\Desktop' is denied.
StackTrace
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, FileShare share)
at System.IO.Compression.ZipFile.Open(String archiveFileName, ZipArchiveMode mode, Encoding entryNameEncoding)
at System.IO.Compression.ZipFile.DoCreateFromDirectory(String sourceDirectoryName, String destinationArchiveFileName, Nullable`1 compressionLevel, Boolean includeBaseDirectory, Encoding entryNameEncoding)
at System.IO.Compression.ZipFile.CreateFromDirectory(String sourceDirectoryName, String destinationArchiveFileName)
at ConsoleApp1.Program.Main(String[] args) in C:\FTG\Projects\CaseWare\ConsoleApp1\Program.cs:line 25
Code
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string[] folders = System.IO.Directory.GetDirectories(#"D:\", "*", System.IO.SearchOption.TopDirectoryOnly);
foreach (string folder in folders)
{
ZipFile.CreateFromDirectory(folder, path); << errors out here!
}
The 2nd parameter string destinationArchiveFileName should be a filename.
for Example "C:\Users\er4505\Desktop\example.zip"
*
Exception =System.Net.WebException: Access to the path
'c:\windows\system32\inetsrv\Dialer' is denied. --->
System.UnauthorizedAccessException: Access to the path
'c:\windows\system32\inetsrv\Dialer' 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) 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, FileAccess access, FileShare share) at
System.Net.FileWebStream..ctor(FileWebRequest request, String path,
FileMode mode, FileAccess access, FileShare sharing) at
System.Net.FileWebRequest.GetRequestStreamCallback(Object state)
--- End of inner exception stack trace --- at System.Net.WebClient.UploadDataInternal(Uri address, String method,
Byte[] data, WebRequest& request) at
System.Net.WebClient.UploadString(Uri address, String method, String
data)
*
Code where the exception is occurring
using (var writer = new StringWriter())
{
JsonSerializer.Create().Serialize(writer, payLoad);
var result =client.UploadString(commDialerApiUrl,writer.ToString());
return ((T)JsonConvert.DeserializeObject(result, typeof(T)));
}
I know the code above is not ideal, however I just need to understand why even an attempt to access is made. Can anyone provide some insight please?
All right, the issue was very simple. The code was trying to make a Restful post to a blank Uri. Since the Uri was blank webclient was trying to resolve the call to a file (having the same name as the service) in inetpub.
Since no such file path was invalid, thus the i/o error.
A new XML file is created and written to in a Python process with the following code:
with open(filepath, 'w') as f:
f.write(inXmlStr)
Subsequently, a C# process is launched by the Python process:
with open(self.outputLogPath, 'w') as f:
self.csharpProcess = subprocess.Popen(processOpenCmd, stdout=f)
This C# process reads this newly created XML file using the XmlDocument class:
XmlDocument chXml = new XmlDocument();
chXml.Load(channelXml);
However, sometimes, the file is found to be locked and cannot be read by the C# process. It is found by using Handle that the process which is locking the XML file is indeed the Python process which had originally created and written to the file. This is unexpected, as the "with" clause of Python is supposed to close any opened files properly. Thus, I suspect this to be a Python bug.
I'm working on Windows 7 with Python 2.7 and .NET Framework 4
The exception stacktrace from the C# process is as follows:
System.IO.IOException: The process cannot access the file 'C:\...\...\channel.xml' because it is being used by another process.
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, FileShare share, Int32 bufferSize)
at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials, IWebProxy proxy, RequestCachePolicy cachePolicy)
at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn)
at System.Xml.XmlTextReaderImpl.OpenUrlDelegate(Object xmlResolver)
at System.Threading.CompressedStack.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.CompressedStack.Run(CompressedStack compressedStack, ContextCallback callback, Object state)
at System.Xml.XmlTextReaderImpl.OpenUrl()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace)
at System.Xml.XmlDocument.Load(XmlReader reader)
at System.Xml.XmlDocument.Load(String filename)
at ChannelXmlRun(String xmlFile)
Any ideas about why this might be happening? Perhaps it is a known Python bug which you can point me to?
I'm trying to edit an opened excel file (by another user in a shared network) in order to make some changes to it and save it back. But when I try to open the file I get the following error :
Message=The process cannot access the file
'Y:\COMMON\SharedFolders\Export.xlsx', because it is being used by another process.
Source=mscorlib
StackTrace:
à System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
à 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)
à System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
à System.IO.File.InternalReadAllBytes(String path, Boolean checkHost)
à System.IO.File.ReadAllBytes(String path)
à OfficeOpenXml.ExcelPackage.ReadFile()
à OfficeOpenXml.ExcelPackage.ConstructNewFile(Stream stream, String password)
à OfficeOpenXml.ExcelPackage..ctor(FileInfo newFile)
By the way, I'm using the EPPLUS library.
You can't. That being said you can look into some "source-safe" solution (like svn, sharepoint or google docs). You can also implement some "poor man" source safe yourself - i.e. small web application that will act as proxy over file system & will allow you to upload file, list folder, download files.
Other option would be to delay update to date when no-one will be accessing that file.
Google allow multiple edit at the same time... maybe you should try to move that file there if possible.
I Have SSIS Variable Expression like this,
#[System::PackageName]+","+
#[System::SourceName]+","+
(DT_STR,15,1252) #[System::ErrorCode]+","+
#[System::ErrorDescription]+","+
(RIGHT((DT_WSTR,4)
DATEPART("yyyy",GetDate()),4)+"/"+
RIGHT("0"+(DT_WSTR , 2)
DATEPART("mm", GetDate()),2)+"/"+
RIGHT("0"+(DT_WSTR,2)
DATEPART("dd",GetDate()),2)+"_"+
RIGHT("0"+(DT_WSTR,2)
DATEPART("HH",GetDate()),2)+":"+
RIGHT("0"+(DT_WSTR,2)
DATEPART("MM",GetDate()),2)+":"+
RIGHT("0"+(DT_WSTR,2)
DATEPART("SS",GetDate()),2))+","+
#[System::MachineName]
Now I want to get some string from #[System::ErrorDescription] which located before at , here's the sample of the #[System::ErrorDescription] value
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.IO.DirectoryNotFoundException: Could not find a part of the path 'D:\blablablabl\yes.txt'.
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, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize)
at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials)
at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn)
at System.Xml.XmlTextReaderImpl.OpenUrlDelegate(Object xmlResolver)
at System.Threading.CompressedStack.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.CompressedStack.Run(CompressedStack compressedStack, ContextCallback callback, Object state)
what i've done is write the substring code on my variable expressions :
SUBSTRING(#[System::ErrorDescription], 1, FINDSTRING(#[System::ErrorDescription], "at", 1)-1)+","+
but its always give me an error , that substring value cannot be negative, whats wrong with my code?
If the result of FINDSTRING(#[System::ErrorDescription], "at", 1) is zero (i.e. string not found) then the last parameter to your substring expression becomes -1. It's a common problem.
Perhaps you could try evaluating whether it is zero, and only use Findstring if it isn't. I have split the expression below for clarity, but it should all be on one line. I don't have SSIS to test but see if it works.
I don't think you've posted your full expression but this should give you the idea.
FINDSTRING(#[System::ErrorDescription], "at", 1)==0
?
"Nothing Found"
:
SUBSTRING(
#[System::ErrorDescription],
1,
FINDSTRING(#[System::ErrorDescription], "at", 1)-1
)
Here's a link that describes conditional:
http://msdn.microsoft.com/en-us/library/ms141680.aspx
I'm not convinced this is the full story, but try it and it will flush out your next issue.