I'm working with print jobs using PrintSystemJobInfo and this class doesn't have the path of the file (print job). So, I was wondering if there is a class where I can use the filename that is open (in memory) and this class return the full path. This file opened could be .doc, .pdf, .xls, .txt, and so on.
Please, someone can point me to the right direction or have an idea... it would be very helpful...
The only way for you to find open file handles is to use the NtQuerySystemInformation call. Here is a project that has this done as an explorer context menu. In this guy's case, he looks for files open in a specific folder.
You would then have to match the file name to the file you have in your print job.
By the way, this is not C# but you can wrap and call the same calls he is using. The rest is really up to you to figure out. ;)
Assuming you have a Stream object that is a FileStream then just do a cast and interrogation:
Stream str = printJob.JobStream;
FileStream fileStream = str as FileStream
if( fileStream != null ) {
String fileName = fileStream.Name;
}
Related
I'm trying to read the contents of a file in a Visual Studio extension. The following code works, but forces me to open the file, if it isn't (otherwise it crashes):
textDocument = (TextDocument)projectItem.Document.Object("TextDocument");
EditPoint editPoint = textDocument.StartPoint.CreateEditPoint();
string text = editPoint.GetText(textDocument.EndPoint);
I can get the path of the project, so I suppose I could make an educated guess as to the location of the project item. However, ideally I'd like to either get the file contents without opening it; or, alternatively, get the path to the project item (then I could just use System.IO to access the file contents).
I've looked, but don't seem to be able to find any mention of either of these. Can anyone point me in the right direction, please?
You can get the path from a ProjectItem by reading its properties.
var path = YourProjectItem.Properties.Item("FullPath").Value.ToString()
After you have the path you can read its content with System.IO.
string content = File.ReadAllText(path);
If the file is somewhat larger and you are getting troubles with the current code due to size, you should take a look at the StreamReader class.
I'm not sure if this is possible for extensions but you could probably use System.IO, like this:
using System.IO;
string filePath = #"C:\Whatever\YourFileName.txt";
string fileText = File.ReadAllText(filePath);
You could also use StreamReader like this:
using System.IO;
string filePath = #"C:\Whatever\YourFileName.txt";
using (StreamReader sr = new StreamReader(filePath))
fileText = sr.ReadToEnd();
EDIT:
I think I understand you better now.
The only way to "get the file contents without opening it" would be if the extension were to give you that data actively, but I can safely assume it doesn't.
When reading a file, you should already know where the file is (if you don't know then either you're not intended to access that file or you just haven't looked long enough).
I'd try searching the SDK files manually (Or with a file crawler).
I'm getting the IOException Error when I try this, and I'm not sure what I'm doing wrong:
This is my code:
FileStream fStream = new FileStream(PDFFilePath(), FileMode.CreateNew, FileAccess.ReadWrite);
Where
private string PDFFilePath()
{
m_sFilePath = "C:/Pictures/";
return m_sFilePath;
}
What am I missing?
I'm using this FileStream to save PDF documents using the Pdf.Select NuGet. It uses a method:
PdfDocument.Save(Stream stream);
I think you should be specifying your path this way:
private string PDFFilePath(string filename)
{
m_sFilePath = #"C:\Pictures\" + filename;
return m_sFilePath;
}
Like #Reisclef said, you have to provide a file path, not a directory. Since you're using FileMode.CreateNew, it has to be a new file, so you might also want to use File.Exists(m_sFilePath) before returning.
You have several problems here.
First, if you use a path like C:\Pictures\, it'll complain about the trailing \.
Secondly, you need to specify an actual file here, not just a directory. It makes no sense to just specify a directory (rather than a file) in this case - that's why it's called a File Stream and not a Directory Stream. I suggest using Path.Combine for this. Also, if you're just trying to move an already-existing file to this directory, you should do File.Move rather than using a FileStream.
Third, you only want to use FileMode.CreateNew if there's no possibility that the file already exists in the destination folder; if it does exist, this will throw an exception.
Fourth, it's a bad practice to hardcode paths like this. You usually want to get the path from a configuration file and make sure that the Pictures directory does, in fact, exist before you try to do this operation; otherwise it may fail when you deploy it to another machine.
Fifth, the PDFFilePath method seems rather pointless in this case - you can do the same thing with a string constant or creating a readonly string in the constructor.
I am doing editor in c#, windows forms. I wish to save 'new content' of file in the same file (usual usage of 'save' option) but I receive IOException, [ the process cannot access the file ' filename' because it is being used by another process.
I have method that writes to a NEW file and it works. How to use it to overwrite current file.
Edit:
I am using binarywriter http://msdn.microsoft.com/en-us/library/atxb4f07.aspx
Chances are that when you loaded the file, you didn't close the FileStream or whatever you used to read it. Always use a using statement for your streams (and other types implementing IDisposable), and it shouldn't be a problem. (Of course if you actually have that file open in a separate application, that's a different problem entirely.)
So instead of:
// Bad code
StreamReader reader = File.OpenText("foo.txt");
string data = reader.ReadToEnd();
// Nothing is closing the reader here! It'll keep an open
// file handle until it happens to be finalized
You should use something more like:
string data;
using (TextReader reader = File.OpenText("foo.txt"))
{
data = reader.ReadToEnd();
}
// Use data here - the handle will have been closed for you
Or ideally, use the methods in File which do it all for you:
string text = File.ReadAllText("foo.txt");
Check if you're closing stream to the file. If not then you're blocking yourself.
Assuming that you have correctly closed the stream you used to open and read the file initially, to create, append or fail depending of file existence you should use the FileMode parameter in FileStream constructor.
Everything depends on the way you open the FileStream, see here: FileStream Constructor (String, FileMode)
if you specify FileMode Create:
Specifies that the operating system should create a new file. If the
file already exists, it will be overwritten. This requires
FileIOPermissionAccess.Write. System.IO.FileMode.Create is equivalent
to requesting that if the file does not exist, use CreateNew;
otherwise, use Truncate. If the file already exists but is a hidden
file, an UnauthorizedAccessException is thrown.
I want to open a MS Word document from my program. At the moment, it can find it when in designer mode but when i publish my program it can't find the file. I believe I need to embed it into my program but I don't know how to do this. This is my current code to open the document:
System.Diagnostics.Process.Start("Manual.docx");
I think the Word document needs to be embedded into the resources of the .exe but i don't know how to to do this.
Can anyone help with some suggestions?
Aaron is pretty right on adding an embedded resource. Do the following to access an embedded resource:
Assembly thisAssembly;
thisAssembly = Assembly.GetExecutingAssembly();
Stream someStream;
someStream = thisAssembly.GetManifestResourceStream("Namespace.Resources.FilenameWithExt");
More info here:
How to embed and access resources by using Visual C#
Edit: Now to actually run the file you will need to copy the file in some temp dir. You can use the following function to save the stream.
public void SaveStreamToFile(string fileFullPath, Stream stream)
{
if (stream.Length == 0) return;
// Create a FileStream object to write a stream to a file
using (FileStream fileStream = System.IO.File.Create(fileFullPath, (int)stream.Length))
{
// Fill the bytes[] array with the stream data
byte[] bytesInStream = new byte[stream.Length];
stream.Read(bytesInStream, 0, (int)bytesInStream.Length);
// Use FileStream object to write to the specified file
fileStream.Write(bytesInStream, 0, bytesInStream.Length);
}
}
Right click the folder where you want to store the file within the Solution and choose Add -> Existing Item.
Once you add the file you can change the Build Action of the file within your project to be an Embedded Resource, versus a Resource. This can be done by going to the Properties within VS of the file and modifying the Build Action property.
Just include it to your project (add existing item) and from the menu that opens, select all files and select your word document. Also Copy the document into your Bin/Debug folder. If you are using an installer, include the document in the installer and it should work.
I have a string with a C# program that I want to write to a file and always overwrite the existing content. If the file isn't there, the program should create a new file instead of throwing an exception.
System.IO.File.WriteAllText (#"D:\path.txt", contents);
If the file exists, this overwrites it.
If the file does not exist, this creates it.
Please make sure you have appropriate privileges to write at the location, otherwise you will get an exception.
Use the File.WriteAllText method. It creates the file if it doesn't exist and overwrites it if it exists.
Generally, FileMode.Create is what you're looking for.
Use the file mode enum to change the File.Open behavior. This works for binary content as well as text.
Since FileMode.Open and FileMode.OpenOrCreate load the existing content to the file stream, if you want to replace the file completely you need to first clear the existing content, if any, before writing to the stream. FileMode.Truncate performs this step automatically
// OriginalFile:
oooooooooooooooooooooooooooooo
// NewFile:
----------------
// Write to file stream with FileMode.Open:
----------------oooooooooooooo
var exists = File.Exists(path);
var fileMode = exists
? FileMode.Truncate // overwrites all of the content of an existing file
: FileMode.CreateNew // creates a new file
using (var destinationStream = File.Open(path, fileMode)
{
await newContentStream.CopyToAsync(destinationStream);
}
FileMode Enum
If your code doesn't require the file to be truncated first, you can use the FileMode.OpenOrCreate to open the filestream, which will create the file if it doesn't exist or open it if it does. You can use the stream to point at the front and start overwriting the existing file?
I'm assuming your using a streams here, there are other ways to write a file.