When i search files through a string in my local drives it shows the following error and it stops to search further.The reason is some of the windows files are used by the OS when the search is in progress.How to overcome this.
The process cannot access the file 'C:\hiberfil.sys'(Hibernate Files) because it is being used by another process.
TextReader rff = null;
rff = new StreamReader(fi.FullName);
try
{
String lne1 = rff.ReadToEnd();
if (lne1.IndexOf(txt) >= 0)
{
z = fi.FullName;
list22.Add(fi.FullName);
You should narrow down your search wildcard to avoid hitting system or locked files or you will always get this exception. In .NET 4.0 you could use the EnumerateFiles method which will perform the search lazily and you could catch the exception.
c:\hiberfil.sys is a system file that is locked against reading. You won't be able to read it because of that. There is no call you can do in c# to determine if a file is locked before you attempt to open it, so put Try/Catch blocks around your attempt to open it and if it throws an exception, just go on to the next file.
TextReader rff = null;
try
{
rff = new StreamReader(fi.FullName);
String lne1 = rff.ReadToEnd();
if (lne1.IndexOf(txt) >= 0)
{
z = fi.FullName;
list22.Add(fi.FullName);
Related
I have built a small web application to read appointments from outlook calendar and i used Microsoft.Office.Interop.Outlook. Now I want to to able to save the attachments which are inside the appointment.
Here is my code so far :
foreach (var item in AppointmentItems) {
for (int i = 1; i <= item.Attachments.Count; i++) {
var Attachment = item.Attachments[i];
string SavePath = Path.Combine(#"D:\SaveTest", Attachment.FileName);
Attachment.SaveAsFile(SavePath);
}
}
Problem :
Exception thrown: 'System.IO.FileNotFoundException at exactly
Attachment.SaveAsFile(SavePath);
I have already looked everywhere, this method should save the attachment to the path but its somehow trying to read a file.
Assuming that the attachment exist, FileNotFoundExecption is triggered by a not existing part of your path. You can check if the path exist first:
Directory.Exists(#"D:\SaveTest")
Then you can check if you have write rights on the directory:
Try
{
return System.IO.Directory.GetAccessControl(#"D:\SaveTest")
.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount))
.Cast<System.Security.AccessControl.FileSystemAccessRule>()
.Where(rule => (System.Security.AccessControl.FileSystemRights.Write & rule.FileSystemRights) == System.Security.AccessControl.FileSystemRights.Write)
.Any(rule => rule.AccessControlType == System.Security.AccessControl.AccessControlType.Allow);
} catch(Exception)
{
return false;
}
3 things you could try to do:
Make sure that the directory exists
Check if Attachment.FileName have valid name and extension
Check your write access
System.IO.FileNotFoundExecption means it can't find the file you are looking for or the path you are trying to save to in your case. remove # and try "D:\foldername\" + attachment.filename. although removing # should still work I think you need use plus operator. Would help you can post the whole block of code so we can understand what is going on from top to bottom.
When I pass the value from the OpenFilePicker() method back to the button click method, I can utilize a debug string and ensure that the value is not null.
However, when I pass it to the GetCellValue() method, a 'FileNotFound' exception is thrown. Utilizing a debug statement here also shows that the value is not null and returns a valid file path of "C:\Test.xlsx".
Tried changing file permissions to RWX for all, attempted different folder locations. All permissions and folders seem to have the same issue.
public async void FileSelectButton_ClickAsync(object sender, RoutedEventArgs e)
{
string filePath = await openFilePicker();
//Debug.WriteLine("result:: " + filePath);
GetCellValue(filePath, "Sheet1", "A1");
}
public async Task<string> openFilePicker()
{
var archerReportPicker = new
Windows.Storage.Pickers.FileOpenPicker();
archerReportPicker.ViewMode =
Windows.Storage.Pickers.PickerViewMode.Thumbnail;
archerReportPicker.SuggestedStartLocation =
Windows.Storage.Pickers.PickerLocationId.Downloads;
archerReportPicker.FileTypeFilter.Add(".xlsx");
archerReportPicker.FileTypeFilter.Add(".xls"); // Default extensions
Windows.Storage.StorageFile archerReport = await archerReportPicker.PickSingleFileAsync(); //Get file
if (archerReport != null)
{
// Application now has read/write access to the picked file
this.fileTextBox.Text = archerReport.Name; // Load it up and throw the data in the textbox.
var filePath = archerReport.Path;
return filePath;
}
else
{
this.fileTextBox.Text = "";
return null;
}
}
public static string GetCellValue(string fileName, string sheetName, string addressName)
{
string value = null;
// Open the spreadsheet document for read-only access.
using (SpreadsheetDocument document = SpreadsheetDocument.Open(fileName, false)) //Line where exception is thrown
{...}
Throws System.IO.FileNotFound Exception as opposed to opening valid file path.
The issue also occurs when filePath or fileName is defined using const string '#c:\test.xlsx'
The short answer to this question is here:
https://blogs.msdn.microsoft.com/wsdevsol/2012/12/04/skip-the-path-stick-to-the-storagefile/
The gist of it is that in UWP, Storage Pickers return a non-filesystem bound Windows.Storage object. You can glean the filesystem path from the object, but because you are performing an operation on a secondary object, the fact that the user gave permissions for the first object does not apply to the second, resulting in an Access Denied condition when attempting to open the file - even if NTFS permissions allow 'Everyone' access.
This can be confirmed by monitoring the application using Process Monitor from SystemInternals.
If I discover a work-around to this issue, I will update this answer, but I will likely move away from UWP back towards a Windows Forms Application to avoid this issue entirely.
private static string getPath(object id11)
{
string wmiQuery = string.Format("select CommandLine from Win32_Process where ProcessId={0}", id11);
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(wmiQuery))
{
using (ManagementObjectCollection retObjectCollection = searcher.Get())
{
foreach (ManagementObject retObject in retObjectCollection)
{
if (retObject["CommandLine"] != null)
{
string s= (string.Format("[{0}]", retObject["CommandLine"]));
string k = s.Substring(s.IndexOf("EXE")+4);
k = k.Remove(k.IndexOf("]"));
return k;
}
return null;
}
return null;
}
}
I use this code to get the notepad full path. This code is work fine when notepad file is open using double click. But When i open file inside notepad like (File->Open)... than this code not work to get a full path. Is there any way to find the path of file open like this. And one more thing i need file path not notepad Executable Path. Or suggest me some other solutions.
Your code looks at the command line arguments sent to a process. As you have rightly found, when you double click a file (.txt or .doc), it may be send as command line argument to the file. Your solution rightly finds the file in those cases.
But, when you open the file from the application, there is no command line argument.
One way is to use a tool like Handle to get the list of process which has your file open.
Sample screen shot:
You can use the Process class to run it and parse the output.
Certain processes (like notepad) will NOT lock the file. So, this tool will not give you the names of those files.
I'm running into some issues trying to move flat HTML files around on a server.
In short, the process says that it should take whatever file is currently in the newpath (if there is one) and move it to the backup folder. Then take the file in the old path and move it to the new path. Then it checks to see if it was successful (i.e. does the newpath exist) and if it wasn't, it replaces the backup. I've pasted the method below for your viewing pleasure.
public bool MoveContent(string oldPath, string newPath, string backupDirectoryPath, out string backupPath)
{
backupPath = String.Empty;
var oldFilePath = HttpContext.Current.Server.MapPath(oldPath);
var newFilePath = HttpContext.Current.Server.MapPath(newPath);
var newDirectory = Path.GetDirectoryName(newFilePath);
// If the file we're moving doesn't exist, fail.
if (!File.Exists(oldFilePath))
throw new InvalidPathException(oldFilePath);
// If no destination is found, fail.
if (string.IsNullOrWhiteSpace(newDirectory))
throw new InvalidPathException(newFilePath);
if (!Directory.Exists(newDirectory))
Directory.CreateDirectory(newDirectory);
var backupPhysicalPath = String.Empty;
// If there is a file in our destination, back that one up.
if (File.Exists(newFilePath) && !String.IsNullOrWhiteSpace(backupDirectoryPath))
{
var backupFilePath = HttpContext.Current.Server.MapPath(backupDirectoryPath);
var backupDirectory = Path.GetDirectoryName(backupFilePath);
// If the backup destination doesn't exist, fail.
if(string.IsNullOrWhiteSpace(backupDirectory))
throw new InvalidPathException(backupDirectory);
if(!Directory.Exists(backupDirectory))
Directory.CreateDirectory(backupDirectory);
var fileName = Path.GetFileNameWithoutExtension(newFilePath);
var currentDateTime = DateTime.Now.ToString(FileHelpers.TempFileDateFormat);
var fileExtension = Path.GetExtension(newFilePath);
// Example Result: hardware-2015-01-30-08-35-26-475.html
backupPath = backupDirectoryPath.Replace(fileName, fileName + "-" + currentDateTime);
backupPhysicalPath = String.Format("{0}\\{1}-{2}{3}", backupDirectory, fileName, currentDateTime, fileExtension);
// If there is already a file in our backup destination, fail.
if (File.Exists(backupPhysicalPath))
throw new InvalidPathException(backupPhysicalPath);
// Backup the file that currently exists in our new destination.
File.Move(newFilePath, backupPhysicalPath);
}
// Move our file to the new destination.
File.Move(oldFilePath, newFilePath);
// Return false if the new file doesn't exist.
if (!File.Exists(newFilePath))
{
// If we made a backup, return the backup to the original loction, since there's nothing in the destination.
if (!String.IsNullOrWhiteSpace(backupPhysicalPath) && File.Exists(backupPhysicalPath))
{
File.Move(backupPhysicalPath, newFilePath);
}
throw new Exception(String.Format("Failed to move content. OldPath: '{0}'; NewPath: '{1}'; BackupPath: '{2}'", oldFilePath, newFilePath, backupPhysicalPath));
}
return true;
}
Here's an example of the parameters being passed in:
oldPath: "/client/content/en/unpublished/Anpan.html"
newPath: "/client/content/en/Anpan.html"
backupDirectoryPath: "/client/content/en/backups/Anpan.html"
The problem that I'm running into is that sometimes the backup file will be made (it will move from newpath to backuppath), but it won't move from oldpath to newpath.
I've been unable to actually reproduce the issue as it happens so infrequently and without any exceptions being thrown, but the symptoms exist (I can see the files on the filesystem when the client reports the issue) and it's been reported multiple times.
I put some logging around it and wrapped the entire method in a try/catch. It never fails unexpectedly (except when I specifically throw the InvalidPathException). There is nothing in my logs when it happens.
Can anyone help me to diagnose this issue, or tell me if I'm doing something very wrong in my method that would cause the problem?
Thanks so much!
I'm kinda new to working with C# .NET's System.IO namespace. So please forgive me for some basic questions.
I am writing an online interface that will allow a site owner to modify files and directories on the server.
I have gotten inconsistent performance out of System.IO.Directory.Delete(PathToDelete, true);. Sometimes it works great, sometimes it throws an error. My controller looks like this:
public ActionResult FileDelete(List<string> entity = null)
{
if (entity != null)
{
if (entity.Count() > 0)
foreach (string s in entity)
{
string CurrentFile = s.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
string FileToDelete = Server.MapPath(CurrentFile);
bool isDir = (System.IO.File.GetAttributes(FileToDelete) & FileAttributes.Directory) == FileAttributes.Directory;
if (isDir)
{
if (System.IO.Directory.Exists(FileToDelete))
{
//Problem line/////////////////////////////////
System.IO.Directory.Delete(FileToDelete, true);
}
}
else
{
if (System.IO.File.Exists(FileToDelete))
{
System.IO.File.Delete(FileToDelete);
string ThumbConfigDir = ConfigurationManager.AppSettings["ThumbnailSubdirectory"];
string ThumbFileToDelete = Path.GetDirectoryName(FileToDelete) + Path.DirectorySeparatorChar + ThumbConfigDir + Path.DirectorySeparatorChar + Path.GetFileName(FileToDelete);
if (System.IO.File.Exists(ThumbFileToDelete))
{
System.IO.File.Delete(ThumbFileToDelete);
}
}
}
}
}
return Redirect(HttpContext.Request.UrlReferrer.AbsoluteUri.ToString());
}
Sometimes, I get an error when tring to delete directories that says:
The directory is not empty.
Description: An unhandled exception occurred during the execution of the current
web request. Please review the stack trace for more information about the error
and where it originated in the code.
Exception Details: System.IO.IOException: The directory is not empty.
Source Error:
Line 137: if (System.IO.Directory.Exists(FileToDelete))
Line 138: {
Line 139: System.IO.Directory.Delete(FileToDelete, true);
Line 140: }
Line 141: }
I'm not sure what kind of defensive coding I can implement to avoid get errors like these. Any thoughts? Am I missunderstanding what it means to set recursive to true by saying System.IO.Directory.Delete(FileToDelete, true);?
If there's a file that's in use, the Delete won't empty the directory, and then will fail when it will try to delete the directory.
Try using FileInfo instead of the static methods, and use Refresh after you do any action on the file. (or DirectoryInfo for direcotries)
Similar problem
In general you just have to expect this sort of exceptions from file/folder manipulation code. There is large number of reasons why it could happen - some file in use, some process have working folder set to the directory, some files are not visible to your process due to permissions and so on.
Process monitor ( http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx) likely will show what causes the problem.
One of common reason if you create folder yourself for your temporary files and then try to delete it is to forget to dispose Stream objects related to files in such folder (could be indirect links by Reader and Writer objets, XmlDocument).