how to find is there a file is open or not and if open then then find its fullpath or directory.
You need to supply more information.
All the File handling classes are in System.IO. You will want to use File or FileInfo.
FileStream fs = new FileStream(file, FileMode.OpenOrCreate, FileAccess.Read, FileShare.None)
try
{
stream.ReadByte();
//file is not open
}
catch (IOException)
{
//it is open
}
Explanation: Open the file, try to read a byte, if it can't we know its either open or readonly.
And to get the full path you can use:
fullPath = System.IO.Path.GetFullPath(path);
Related
When I open an excel file, a hidden temporary file is generated in the same folder. I can open it with the TotalCommander Viewer, but I always get an IO exception when trying to open with powershell or c#.
new FileStream(#"D:\~$test.xlsx", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
System.IO.IOException: 'The process cannot access the file 'D:~$test.xlsx' because it is being used by another process.'
So how can I get the content?
Unfortunately for some reason you can not open the direct file, so I suggest another method when you copy a the file to a temp file, then read it and finally you delete the temp file, this way you can read it, I suppose TotalCommander uses the same method for opening files in Viewer.
static void Main(string[] args)
{
CopyReadAndDelete(#"c:\Documents\~$test.xlsx");
}
static void CopyReadAndDelete(string filePath)
{
var tempFileFullPath = Path.Combine(Path.GetDirectoryName(filePath), Guid.NewGuid().ToString());
File.Copy(filePath, tempFileFullPath);
try
{
using (var sr = new StreamReader(tempFileFullPath))
{
Console.WriteLine(sr.ReadToEnd()); //or do anything with the content
}
}
finally
{
File.Delete(tempFileFullPath);
}
}
So i have this console app that looks through a folder for files, this folder only has .tiff images and the whole point of the app is convert them all into pdf files and finally merge them, and so I have this foreach cycle
foreach (var path in Directory.GetFiles(#"C:/Users/tferreira/Desktop/TIF_MarcadAgua"))
{
Console.WriteLine(path); // full path
Console.WriteLine(System.IO.Path.GetFileName(path)); // file name
Escrever("A fazer pdf");
imagens.Add(path.ToUpper().Replace("A.TIF", "A.PDF").Replace("A.tif", "A.PDF"));
FazerPdf(path);
if (File.Exists(path.ToUpper().Replace("A.TIF", "B.TIF")))
{
imagens.Add(path.ToUpper().Replace("A.TIF", "B.PDF"));
FazerPdf(path.ToUpper().Replace("A.TIF", "B.TIF"));
}
Escrever("O pdf foi gerado com sucesso. Caminho : " + path.ToUpper().Replace("A.TIF", "A.PDF").Replace("A.tif", "A.PDF"));
Escrever("Vai fazer o merge de todos os pdfs gerados.");
PdfMerge pm = new PdfMerge();
foreach (string imagem in imagens)
{
pm.AddDocument(imagem);
npages++;
}
}
And what is does is run trough the folder getting all the files and storing the path in that var path variable.
But when it´s actually time to make the pdf it gives that error i mentioned up top.
The line the error happens is this the fazerPDF funtion, thats where the pdf is made, since its a filepath error i will only show the error line since it keeps things easy to see.
using (FileStream stream = new FileStream(Path.Replace("TIF", "PDF"), FileMode.Create, FileAccess.Write))
{
// some code
}
Things i know, the images do exist, the folder does exist.
Thanks for the help, if i myself find out what it is ill post a answer.
EDIT:
fazerPDF function
static public void FazerPdf(string Path)
{
string newPath = System.IO.Path.ChangeExtension(Path, ".pdf");
if (!File.Exists(Path.Replace("TIF", "PDF")))
using (FileStream stream = new FileStream(newPath.Replace("TIF", "PDF"), FileMode.Create, FileAccess.Write))
{
The problem seems to be this line:
using (FileStream stream = new FileStream(Path.Replace("TIF", "PDF"), FileMode.Create, FileAccess.Write))
This will replace all instances of "TIF" in Path with "PDF", no matter where they appear. For example:
c:\TIFs\IlikeTIFfiles\MyTIF.TIF
Would become:
c:\PDFs\IlikePDFfiles\MyPDF.PDF
If you simply want to replace the file extension part of the path, you can use Path.ChangeExtension to cut off the old extension and add the new one:
string newPath = System.IO.Path.ChangeExtension(path, ".pdf");
using (FileStream stream = new FileStream(newPath, FileMode.Create, FileAccess.Write))
Taking the example above, #"c:\TIFs\IlikeTIFfiles\MyTIF.TIF" would become #"c:\TIFs\IlikeTIFfiles\MyTIF.pdf"
See it in action.
I want to open a file which is saved in my local directory folder in asp.net c#.
I have tried filestream like this:
path = TreeView1.SelectedNode.Value.ToString(); // file path (D:\projects\Content\Media\xxxx.PDF )
if (IsPostBack)
{
path = TreeView1.SelectedNode.Value.ToString();
FileInfo fileInfo = new FileInfo(path);
if (fileInfo.Exists)
{
FileStream fileStream = fileInfo.Open(FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(fileStream);
}
}
As per my understanding of your question you are trying open the file means you are trying to launch the file
If i am right use this
System.Diagnostics.Process.Start(#"Your_PDF_File_Path");
Edit:Here is an easy option for displaying pdf file in html5.
<embed src="Your_File.pdf" width="800px" height="2100px">
The following code works for me when i have a fixed file+filepath declared in my code and is understood to work.
NetworkStream netStream = client.GetStream();
string FileName = #"D:\John\FYL\video1.mp4";
Directory.CreateDirectory(Path.GetDirectoryName(FileName));
using (FileStream fs = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write))
{
netStream.CopyTo(fs);
}
netStream.Close();
}
But fails for this protion.
NetworkStream netStream = client.GetStream();
// FileName is taken at run time on button click from textbox.
using (FileStream fs = new FileStream(#"D:\John\FYL\"+FileName, FileMode.OpenOrCreate, FileAccess.Write))
{
netStream.CopyTo(fs);
}
netStream.Close();
}
Now when i checked another case, using File.Create and getting FileName at run-time it works.
FileStream output = File.Create(#"D:\John\" + FileName)
I'm in doubt because i have to get the saving location at run-time from Browse dialog but why FileStream fs = new FileStream(#"D:\John\FYL\+FileName throws exceptions like System.IO.DirectoryNotFoundException and System.UnauthorizedAcessException although i changed security settings for my local drives.
Does thread affecting all this as this code is a part of code loaded at run-time and browse is a click event ?
You need to ensure that the directory exists before trying to create the file.
NetworkStream netStream = client.GetStream();
if (!Directory.Exists(#"D:\John\FYL\" + FileName)) {
Directory.CreateDirectory(#"D:\John\FYL\" + FileName);
}
using (FileStream fs = new
FileStream(#"D:\John\FYL\" + FileName, FileMode.OpenOrCreate, FileAccess.Write))
{
netStream.CopyTo(fs);
}
netStream.Close();
You may also want to check that the variable FileName is properly formatted. Since you are already providing a trailing backslash "D:\John\FYL\", check that FileName is not \File1.mp4, which will concatenate into "D:\John\FYL\\File1.mp4", which is incorrect.
have you tried looking at the value of FileName? probably it's giving wrong value.
If File name contains only the name of the file, then be sure to give the name along with file extension, if there isn't any extension provided, your program will treat the name as a directory extension which it is not able to find.
If the File name contains the name along with directory heirarchy then you are simply concatenating one directory to your "D:\John\" directory which again is wrong.
I'm monitoring a folder for new files, and when the new file is present I read (and save in a txt) the file as following:
FileStream file = File.Open(this.filePath, FileMode.Open, FileAccess.Read);
StreamReader reader = new System.IO.StreamReader(file);
string text = reader.ReadToEnd();
reader.Close();
If I copy/paste in the folder the source file, I receive an IOExcpetion that tells me that the file is used by another process.
If I cut/paste in the folder, all works.
Moreover locking problem happens also If I copy (but also cut in this case)/paste the file from another machine into the monitored folder.
Do you have an idea about what is happening?
There is a safer way to access to the file in order to avoid this type of locks?
Thanks!
Here is a little snippet I do to ensure the file is finished copying or not in use by another process.
private bool FileUploadCompleted(string filename)
{
try
{
using (FileStream inputStream = File.Open(filename, FileMode.Open,
FileAccess.Read,
FileShare.None))
{
return true;
}
}
catch (IOException)
{
return false;
}
}
Then you can implement this before your process logic
while (!FileUploadCompleted(filePath))
{
//if the file is in use it will enter here
//So you could sleep the thread here for a second or something to allow it some time
// Also you could add a retry count and if it goes past the allotted retries you
// can break the loop and send an email or log the file for manual processing or
// something like that
}