How to find and copy .pdf file to clipboard - c#

I'm trying to copy a pdf file to the clipboard so I can later paste it by Ctrl+V.
The following code can find a file but I'm not sure how to copy it to the clipboard.
How can I copy a pdf file once it is found?
private void copyToClipbard_Click(object sender, RoutedEventArgs e)
{
var file = Directory.GetFiles(#"C:\MyFolder\", "myPDFFile.pdf", SearchOption.AllDirectories).FirstOrDefault();
Clipboard.SetDataObject(file);
}
I get error:
An unhandled exception of type 'System.ArgumentNullException' occurred in PresentationCore.dll
EDIT: I also tried the following, I don't get any errors but it doesn't copy the file.
EDIT: The following code does work, I was not putting the right path, I like jasttims answer better though.
private void copyToClipbard_Click(object sender, RoutedEventArgs e)
{
var file = Directory.GetFiles(#"C:\MyFolder\", "myPDFFile.pdf", SearchOption.AllDirectories).FirstOrDefault();
var dataObj = new DataObject();
string[] fileName = new string[1];
fileName[0] = file;
dataObj.SetData(DataFormats.FileDrop, fileName, true);
Clipboard.SetDataObject(dataObj, true);
}

Try using the "Clipboard" class.
It features all the methods necessary for putting data on the Windows clipboard.
StringCollection paths = new StringCollection();
paths.Add("c:\file.pdf");
Clipboard.SetFileDropList(paths);

Related

How to fix "The process cannot access the file 'C:\Folder\New Text Document.txt' because it is being used by another process"?

I am getting this error when a new file is added to a folder:
The process cannot access the file 'C:\Folder\New Text Document.txt' because it is being used by another process.
I am trying to find a solutions here on SO but none has worked for me. My code at the moment now is:
private void fileSystemWatcher1_Created(object sender, FileSystemEventArgs e)
{
fileWatcher1.Items.Add(string.Format("File Created: {0} File Name: {1}", e.FullPath, e.Name)).ForeColor = Color.Green;
}
EDIT
The error gets thrown here:
using (var fileStream = File.OpenRead(e.FullPath)) --> HERE
{
BinaryReader reader = new BinaryReader(fileStream);
file = reader.ReadBytes((int)fileStream.Length);
fileStream.Close();
}
So every time I add a new file I get the above error?
Thanks
The file may be opened in your system. Make sure its closed/deleted.
https://learn.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher.created?view=netframework-4.8

Access to Path for Documents Folder denied when creating text document

I am trying to make a text file in my documents
private void SaveButton_Click(object sender, EventArgs e)
{
string path = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
StreamWriter sw = File.CreateText(path);
sw.WriteLine("Hello!");
}
It says that path is denied
You're getting an access denied error because File.CreateText() expects a full path to the file that should be created. The code is giving it the path to your Documents folder. Since that path already exists and is a folder, that is the cause of the access denied error.
You should change path to point to a non-existent text file first. Also, StreamWriter.Dispose() needs to be called in order to close the file (this is typically done with a using statement).
private void SaveButton_Click(object sender, EventArgs e)
{
string path = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
path = Path.Combine(path, "MyFile.txt");
using(StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Hello!");
}
}
You have not given the path to the file you are trying to create; only the folder itself. Instead you could do something like
using (StreamWriter sw = File.CreateText(path + $"\hello.txt"))
sw.WriteLine("Hello!");

C# error saving Excel file

I'm pretty new to C# and I'm experimenting a lot, I'm trying to make my program a little more user friendly and that is where the problem starts.
At first the location of the excelfile was in a public static string and I had no problems. I've changed it to this:
public string Excellocation()
{
string xlLocation;
if (but_Browse.Text == "Zoek Excel")
{
xlLocation = #"E:\Levi\Documents\Verjaardagen.xlsx";
}
else //Only if I get into this part of my code I get the error
{
xlLocation = but_Browse.Text;
}
return xlLocation;
}
And the button I use so the user can give me a location for the excel file is:
private void but_Browse_Click(object sender, EventArgs e)
{
var FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string fileToOpen = FD.FileName;
System.IO.FileInfo File = new System.IO.FileInfo(FD.FileName);
//OR
System.IO.StreamReader reader = new System.IO.StreamReader(fileToOpen);
//etc
but_Browse.Text = fileToOpen;
this.but_Browse.AutoSize = true;
But_Import.Visible = true;
}
}
Reading the Excel-file is no problem, my program finds it and processes it, if and only if the user changed the location by using the "Browse button" I get a message from Windows that there is already an excel file with that name and if I want to replace it, If I click away that message, my code gives an error on the line that tries to save the excel file
xlWorkbook.Save();
xlWorkbook.Close(true);
xlApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
xlWorkbook.Save() gives me this error:
System.Runtime.InteropServices.COMException occurred
HResult=0x800A03EC Message=Verjaardagen.xlsx can not be saved,
because it's read-only.
I have no idea why I don't get an error with the default location while I do get an error if use my button to give me that same location.
Does anyone know what i'm doing wrong?
Thanks in advance
So the problem is that the file is read only when you try to write to it after going through but_Browse_Click? Are you closing the StreamReader? Try using
reader.close();
in but_Browse_Click.
Perhaps a better way would be:
using (StreamReader reader = new StreamReader(fileToOpen))
{
//all code involving the reader in here
}
This automatically closes on completion.

Getting File path from a open file dialog

I want to make a button that
opens a file from some location in file system,
gets its file path,
pass the file path like an argument to a method
open that file and do something with it.
I've made a button like this:
private void button1_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog fDialog = new OpenFileDialog();
fDialog.Title = "Open XML file";
fDialog.Filter = "XML files|*.config";
fDialog.InitialDirectory = #"C:\";
fDialog.ShowDialog();
}
I already made a method that reads from hard-coded location, but can someone help me about that file path part variable?
Method reads file with XmlTextReader like this:
private void ReadAdvancedConfigFile()
{
XElement root = null;
root = XElement.Load(new XmlTextReader(#"C:\Users\nemanja.mosorinski\Downloads\__Research-master\__Research-master\SEDMSVSPackage\VisualStudioPackage\AppRes\ConfigFiles\Unity.config"));
}
So basically I want to put new file path for some file founded by OpenFileDialog in root variable.
Change this line:
fDialog.ShowDialog();
To:
bool? control = fDialog.ShowDialog();
if(control.Value)
{
var filePath = fDialog.FileName;
ReadAdvancedConfigFile(filePath)
}
Also you should change the method signature
private void ReadAdvancedConfigFile(string path)

File Copy in C#.Net

I'm trying to build a copier so that you use the openFileDialog to chose a file and then the folderBrowserDialog to choose the location to copy it to.
The problem I'm having is that when I use File.Copy(copyFrom,copyTo) it gives me an exception that I can't copy to a directory.
Is there anyway around this, or am I just missing something stupid and noobish. I've tryed useing openFD for choosing both locations and have just tried using the folderBD to see if it made a difference.
I know there should be if statements there to catch the exceptions but this is a rough draft of the code to get working 1st.
Thanks in advance for the help, code attached.
// Declare for use in all methods
public string copyFrom;
public string copyTo;
public string rootFolder = #"C:\Documents and Settings\cmolloy\My Documents";
private void btnCopyFrom_Click(object sender, EventArgs e)
{
// uses a openFileDialog, openFD, to chose the file to copy
copyFrom = "";
openFD.InitialDirectory = rootFolder;
openFD.FileName = "";
openFD.ShowDialog();
// sets copyFrom = to the file chosen from the openFD
copyFrom = openFD.FileName;
// shows it in a textbox
txtCopyFrom.Text = copyFrom;
}
private void btnCopyTo_Click(object sender, EventArgs e)
{
//uses folderBrowserDialog, folderBD, to chose the folder to copy to
copyTo = "";
this.folderBD.RootFolder = System.Environment.SpecialFolder.MyDocuments;
this.folderBD.ShowNewFolderButton = false;
folderBD.ShowDialog();
DialogResult result = this.folderBD.ShowDialog();
// sets copyTo = to the folder chosen from folderBD
copyTo = this.folderBD.SelectedPath;
//shows it in a textbox.
txtCopyTo.Text = copyTo;
}
private void btnCopy_Click(object sender, EventArgs e)
{
// copys file
File.Copy(copyFrom, copyTo);
MessageBox.Show("File Copied");
You have to append the file name to the directory path. Do this:
string destinationPath = Path.Combine(copyTo, Path.GetFileName(copyFrom));
File.Copy(copyFrom, destinationPath);
(with this you'll copy selected file to another directory with the same name of the original one and it'll throw an exception if the same file already exist in that directory)
Edit
Side note: do not hard code the path in your source code, use this:
rootFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
to get the path of current user's documents folder.
Do this:
File.Copy(copyFrom, Path.Combine(copyTo, Path.GetFileName(copyFrom)));
File.Copy needs to know the full path of the new file you want, including the file name. If you just want to use the same file name, you can use this to append the file name to the path:
copyTo = Path.Combine(copyTo, Path.GetFileName(copyFrom));

Categories

Resources