Sometimes I get a clipboard error. I've researched this and found that there is a better way to do this, but being new I can't figure out how to integrate it in my code. Trying to make it more stable.
Tried multiple ways to convert the information. Looking to fix this not rewrite everything. I have been down many paths with no luck.
void exportagfile()
{
if (editgrid.Items.Count == 0)
{
MessageBox.Show("Nothing to export.");
}
else
{
try
{
editgrid.SelectAllCells();
editgrid.ClipboardCopyMode =
DataGridClipboardCopyMode.ExcludeHeader;
ApplicationCommands.Copy.Execute(null, editgrid);
String resultat2 =
(string)Clipboard.GetData(DataFormats.CommaSeparatedValue);
String result2 =
(string)Clipboard.GetData(DataFormats.Text);
editgrid.UnselectAllCells();
System.IO.StreamWriter file2 = new
System.IO.StreamWriter
(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) +
#"\MI_imp.txt");
file2.WriteLine(result2.Replace('\t', ',').Replace('»',
','));
file2.Close();
MessageBox.Show(" Exporting File MI_imp.txt to Desktop");
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
}
Trying to stop error when clipboard tries to open. Error: System.Runtime.InteropServices.COMExeption (0x800401D0) OpenClipboard Failed
Related
I am trying to open a file, and I would like to return e.g. X if the filepath does not exist, Y if the file can't be opened, and Z if it was successful.
However, I can't understand how I can check for the "file can't be opened" error and I am not sure my try-catch is correct so far. I would also like to add another statement to check if the file is already open.
public int Opener(string fileName)
{
string text = "";
try
{
text = File.ReadAllText(fileName);
return "Something to Return";
}
catch (FileNotFoundException)
{
return "Something to Return";
}
You can use this to check the cases you described:
try
{
string text = File.ReadAllText(fileName);
//Z: reading was successful
}
catch (Exception ex)
{
if (ex.InnerException is IOException)
{
//Y: file is already being read
}
else if (ex.InnerException is FileNotFoundException)
{
//X: file does not exist
}
}
The function is declared to return an int, so you need a number there, like -1, 0, or 1. If you want to return a text error message, change the function return type to string.
I have what I thought would be a very simple file mover script. It checks for a file and moves it to a new directory if it exists:
if (File.Exists(_collection[x,0]))
{
System.IO.File.Move(_collection[x, 0], _moveTo);
MessageBox.Show("File moved because it was stale.");
}
It passes the check that the file exists, but then errors on the following line when trying to move it stating that the file is being used by another process. I can only assume that File.Exists is causing it to hang up somehow, but can't find a solution from anyone else who had this problem.
try this code:
string filePathNameToMove = "";
string directoryPathToMove = "";
if (File.Exists(filePathNameToMove))
{
string destinationFilePathName =
Path.Combine(directoryPathToMove, Path.GetFileName(filePathNameToMove));
if (!File.Exists(destinationFilePathName))
{
try
{
File.Move(filePathNameToMove, destinationFilePathName);
Console.WriteLine("File Moved!");
}
catch (Exception e)
{
Console.WriteLine("File Not Moved! Error:" + e.Message);
}
}
}
In case anyone else has this problem. In my case, the file had been opened in Excel and Excel was never garbage collected after being terminated. So the OS still thought the file was being accessed. I did the following, crude, but it works.
for (int i = 1; i > 0; i++)
{
try
{
File.Move(sourceFileName, destinationFileName);
break;
} catch
{
GC.Collect();
}
}
I am using StreamWriter to write a file in a sessionchange like logon and logoff.
But if a reboot happens just about the time when we write/close the file, we are getting an empty file and some time data already in it is getting deleted
This is my code
public void ToJson(T objectToWrite)
{
InformFileLogger.Instance.Debug(">>> start >>>");
try
{
string json = null;
string directory = Path.GetDirectoryName(this.serializeFilePath);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
if (File.Exists(this.serializeFilePath))
{
if (new FileInfo(this.serializeFilePath).Length == 0)
{
File.Delete(this.serializeFilePath);
}
}
json = JsonConvert.SerializeObject(objectToWrite);
if (json != null)
{
using (StreamWriter streamWriter = new StreamWriter(this.serializeFilePath))
{
streamWriter.WriteLine(json);
streamWriter.Close();
}
}
}
catch (Exception ex)
{
InformEventLogger.Error(ex.ToString());
InformFileLogger.Instance.Error(InformHelper.ExceptionMessageFormat(ex));
}
InformFileLogger.Instance.Debug("<<< end <<<");
}
How can I avoid writing null entries in the files/ getting the data deleted?
This really depends on how the reboot is triggered.
Unless the reboot is triggered by your code, you won't be able to make sure your code can do anything before a reboot - including completing a StreamWriter function.
I am in a Highschool club where we create windows store apps. I am in charge of the code that allows the user to either download files from their online onedrive storage, or upload files. So far I have successfully logged the user in and gained access to onedrive and display the users name with the following code:
private async void LoadProfile()
{
bool connected = false;
string text = "No Error:";
try
{
var authClient = new LiveAuthClient();
LiveLoginResult result = await authClient.LoginAsync(new List<string>() {"wl.signin", "wl.skydrive"});
if (result.Status == LiveConnectSessionStatus.Connected)
{
connected = true;
var connectClient = new LiveConnectClient(result.Session);
var meResult = await connectClient.GetAsync("me");
dynamic meData = meResult.Result;
Textblock_profilename.Text = meData.name;
}
}
catch (LiveAuthException ex)
{
//Set text to corresponding error
text = ex.ToString();
}
catch (LiveConnectException ex)
{
//Set text to corresponding error
text = ex.ToString();
}
if (text[0].ToString() != "N")
{
var dialog = new Windows.UI.Popups.MessageDialog(text);
await dialog.ShowAsync();
}
}
I gained the code from the following MSDN tutorial: http://msdn.microsoft.com/en-us/library/dn631823.aspx
However when I try to follow the next step, downloading and uploading files, I cannot get it to work. Right now I am just trying to press a button, and have the code download a test file:
private async void Button_downloadFile_Click(object sender, RoutedEventArgs e)
{
try
{
LiveDownloadOperation operation = await connectClient.CreateBackgroundDownloadAsync("skydrive/documents/enter_path");
var result = await operation.StartAsync();
//DO SOMETHING WITH RESULT HERE
}
catch
{
// Handle any errors.
}
}
However this code throws the following errors:
This is straight from the MSDN tutorial, and can't figure out how to fix the error. My best guess is I'm missing a "using" statement, but can't figure out what I am missing. Thanks for any and all help!
Make sure you're updated to use the Live SDK 5.6 binary. Be sure to let us know if you have any other problems with OneDrive integration!
Here is my code
if (row.Cells[5].Value.ToString().ToUpper() == "JPG")
{
try
{
// string notepadPath = Path.Combine(Environment.SystemDirectory, "MSPAINT.exe");
string notepadPath = Path.Combine(Environment.SystemDirectory, "JPEGViewer.exe");
if (File.Exists(notepadPath))
Process.Start(notepadPath, location);
else
throw new Exception("Can't locate Notepad");
}
catch (Exception ee)
{
MessageBox.Show("Exception is " + ee.Message);
}
}
Even Though the String notepadPath contains the Folder and executable C:\Windows\system32\JPEGViewer.exe the line ** if (File.Exists(notepadPath)) doesn't find the exe even though it is there. If I attempt to bypass the Exist and perform the Process.Start(notepadPath, location); It throws an exception The system cannot find the file specified
**
Please note that this same code works perfectly when calling MSPAINT.EXE
Any ideas will be greatly appreciated,