'System.IO.FileNotFoundException' when trying to save an outlook Attachment - c#

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.

Related

How to add value to a custom column while uploading document into a SharePoint document library as an item using C#?

I have a console application which tries to upload a document into a share point document library list.
I am successfully able to do it and also I am able to fill one of the custom Column(Column name is : "Category") value while uploading the file using C#.
I have tried to fill another custom column(Column name is : "Related Assets") value using the same procedure but i get the error stating the provided column name does not exist but when i see in actual share point portal it does exist.
So not able to solve this issue. Even i tried couple of methods as given below and i get same error message in terms of the column does not exist or it has been deleted or not able to recognize it.
Please find the screenshot of SharePoint showing the list of columns:
Please find the code i have till now which upload the document into SharePoint portal.
public static async Task<string> UploadReleaseNoteDocumentintoSpPortal(string releasenotefilepath, string releasenotefilename, string clientid, string clientsecret)
{
string status = string.Empty;
try
{
Console.WriteLine("Trying to Upload Release note file into Share Point Portal...");
string siteUrl = "<<Sp site URL>>";
Console.WriteLine("Connecting to Share Point Portal...");
var ClientContext = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(siteUrl, clientid, clientsecret);
ClientContext.Load(ClientContext.Web, p => p.Title);
await ClientContext.ExecuteQueryAsync();
Console.WriteLine(ClientContext.Web.Title);
var web = ClientContext.Web;
Console.WriteLine("Connected successfully to Share Point Portal...");
List DocumentsList = web.Lists.GetByTitle("Accelerators Documents");
ClientContext.Load(DocumentsList.RootFolder);
await ClientContext.ExecuteQueryAsync();
Console.WriteLine("Reading and loading the list named : Accelerators Documents from SP");
Console.WriteLine("Converting the release note document into byte array");
byte[] bytes = System.IO.File.ReadAllBytes(releasenotefilepath);
MemoryStream stream = new MemoryStream(bytes);
Console.WriteLine("Storing the release note Data into File Create information object of SharePoint");
FileCreationInformation FileCreateInfo = new FileCreationInformation();
FileCreateInfo.Content = bytes;
FileCreateInfo.ContentStream = stream;
FileCreateInfo.Overwrite = true;
FileCreateInfo.Url = DocumentsList.RootFolder.ServerRelativeUrl + #"\" + releasenotefilename;
Console.WriteLine("Adding file to SharePoint");
var ReleaseNoteFiledata = DocumentsList.RootFolder.Files.Add(FileCreateInfo);
ReleaseNoteFiledata.Update();
ReleaseNoteFiledata.ListItemAllFields["Category"] = "Release Notes";
//ReleaseNoteFiledata.ListItemAllFields["Related Assets"] = "<<Desired Value>>";
//IN Above commented line i get the error stating Microsoft.SharePoint.Client.ServerException:
//'Column 'Related Assets' does not exist. It may have been deleted by another user.
//But in actual site if we see it exists as you can see in above screenshot
ReleaseNoteFiledata.ListItemAllFields.Update();
ClientContext.Load(ReleaseNoteFiledata);
await ClientContext.ExecuteQueryAsync();
Console.WriteLine("Adding file to SharePoint Completed Successfully...");
return status = "Successful";
}
catch (Exception ex)
{
Console.WriteLine("Exception occured while trying to upload Release note file into CoP Portal :" + ex.Message);
return status = "Error/Exception";
}
}
Please find the error message i get while trying to add value to another custom column present in SharePoint:
Microsoft.SharePoint.Client.ServerException: 'Column 'Related Assets' does not exist. It may have been deleted by another user.
Even if i use the ReleaseNoteFiledata.SetFileProperties() and pass the values as a dictionary key value pair containing the column name and its value then also i get the same error for the second custom column. If i keep only the category custom column then it works perfectly without any issue as you can see in the screenshot above.
If i select the record and see the details or properties in the SharePoint the Related assets column symbol is some like in below screenshot:
Please let me know if the supporting documents are fine or still if my issue is not understandable so that i can re frame it or provide more screenshots.
Please help me in solving the above issue or how to make this column recognizable or readable or identifiable in the code.
Thanks in Advance
Regards
ChaitanyaNG
You need to use the internal name of the column 'Related Assets' in your code. It should be Related_x0020_Assets.
You could check the internal name of the column by go to list settings-> click the column, you would see the internal name in the url.

TFS - Get latest code in a folder

I am using the TFS API to get latest code files, directories, .csproj files, etc. under a TFS-bound folder.
For the same, I use something like the following:
var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new
Uri(ConfigurationManager.AppSettings["TFSUrl"]));
tfs.EnsureAuthenticated();
var vsStore = tfs.GetService<VersionControlServer>();
string workingFolder = #"C:\TFS\SolutionFolder";
Workspace wsp = vsStore.TryGetWorkspace(workingFolder);
if (wsp != null)
{
ItemSet items = vsStore.GetItems(workingFolder, VersionSpec.Latest, RecursionType.Full);
string relativePath = workingFolder + #"/";
foreach (Item item in items.Items)
{
string relativePath1 = item.ServerItem.Replace("$/TFS/SolutionFolder", relativePath);
if (item.ItemType == ItemType.Folder)
{
Directory.CreateDirectory(relativePath1);
}
else
{
item.DownloadFile(relativePath1);
}
}
}
Now, I get the items to download and then download happens. However, I want it to be like how VS handles it - if (and only if) there is a change in a file/folder, then only download the same. With this code, I always get 'n' number of files/folders in that folder and then I overwrite the same. Wrong approach, I know. I can, however, modify this code to check for the folder's or file's last change time and then choose to either overwrite it or ignore it. That's an option, albeit a bad one at that.
Now, what I would ideally like is to get ONLY the list of files/folders that actually need to be changed i.e. the incremental change. After that, I can choose to overwrite/ignore each item in that list. So, in the present case, if a new file/folder is created (or one of the existing ones got changed inside $/TFS/SolutionFolder i.e. in the sever), then only I want to pull that item in the list of files/folders to change(and decide what I want to do with it inside C:\TFS\SolutionFolder).
Also, is using one of the overloads of VersionControlServer.QueryHistory() an option? I had something like this:
(latestVersionIdOf $/TFS/SolutionFolder) - (existingVersionIdOf C:\TFS\SolutionFolder) = (Versions that I'd go out and get back from the server, for that folder)
in mind.
Any pointers will be very helpful. Thanks!
Just use Workspace.Get() or overload method (wsp.Get()), it just update updated files.
I don't think we can achieve that. If the files are downloaded to a folder without in source control, there are no versions compared within the folder, even if the folder is in source control, the behavior is just download also no version compare actions. So, it will download all the files ever time and then overwrite the same ones.
In VS, the files are all in TFS source control system, so when we Get Latest Version the changed/added files will be retrieved from TFS. If you want to get the same behavior as VS handles, you can use the tf get command. See Get Command
You can reference this article to use the tf get command :
get-latest-version-of-specific-files-with-tfs-power-tools
Update :-
var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(ConfigurationManager.AppSettings["TFSUrl"]));
tfs.EnsureAuthenticated();
var vsStore = tfs.GetService<VersionControlServer>();
string workingFolder = ConfigurationManager.AppSettings["LocalPathToFolder"]; // C:\TFS\SolutionFolder
string tfsPathToFolder = ConfigurationManager.AppSettings["TFSPathToFolder"]; // $/TFS/SolutionFolder
Workspace wsp = vsStore.GetWorkspace(workingFolder);
if (wsp != null)
{
ItemSpec[] specs = { new ItemSpec(tfsPathToFolder, RecursionType.Full) };
ExtendedItem[][] extendedItems = wsp.GetExtendedItems(specs, DeletedState.NonDeleted, ItemType.Any);
ExtendedItem[] extendedItem = extendedItems[0];
var itemsToDownload = extendedItem.Where(itemToDownload => itemToDownload.IsLatest == false);
foreach (var itemToDownload in itemsToDownload)
{
try
{
switch (itemToDownload.ItemType)
{
case ItemType.File:
if (itemToDownload.LocalItem != null)
{
vsStore.DownloadFile(itemToDownload.SourceServerItem, itemToDownload.LocalItem);
}
else
{
string localItemPath = itemToDownload.SourceServerItem.Replace(tfsPathToFolder,
workingFolder);
vsStore.DownloadFile(itemToDownload.SourceServerItem, localItemPath);
}
break;
case ItemType.Folder:
string folderName = itemToDownload.SourceServerItem.Replace(tfsPathToFolder, workingFolder);
if ((!string.IsNullOrEmpty(folderName)) && (!Directory.Exists(folderName)))
{
Directory.CreateDirectory(folderName);
}
break;
}
}
catch (Exception e)
{
File.AppendAllText(#"C:\TempLocation\GetLatestExceptions.txt", e.Message);
}
}
}
This code works well, except:
a. Whenever it downloads the latest copy of, let's say a file, it 'checks it out' in TFS :(
b. For some items, it throws errors like 'Item $/TFS/SolutionFolder/FolderX/abc.cs was not found in source control at version T.' - I have to find out what the exact cause of this issue is, though.
Any ideas on how to get around these two issues or any other problems you see with this code? Thanks!

Why does my file sometimes disappear in the process of reading from it or writing to it?

I have an app that reads from text files to determine which reports should be generated. It works as it should most of the time, but once in awhile, the program deletes one of the text files it reads from/writes to. Then an exception is thrown ("Could not find file") and progress ceases.
Here is some pertinent code.
First, reading from the file:
List<String> delPerfRecords = ReadFileContents(DelPerfFile);
. . .
private static List<String> ReadFileContents(string fileName)
{
List<String> fileContents = new List<string>();
try
{
fileContents = File.ReadAllLines(fileName).ToList();
}
catch (Exception ex)
{
RoboReporterConstsAndUtils.HandleException(ex);
}
return fileContents;
}
Then, writing to the file -- it marks the record/line in that file as having been processed, so that the same report is not re-generated the next time the file is examined:
MarkAsProcessed(DelPerfFile, qrRecord);
. . .
private static void MarkAsProcessed(string fileToUpdate, string
qrRecord)
{
try
{
var fileContents = File.ReadAllLines(fileToUpdate).ToList();
for (int i = 0; i < fileContents.Count; i++)
{
if (fileContents[i] == qrRecord)
{
fileContents[i] = string.Format("{0}{1} {2}"
qrRecord, RoboReporterConstsAndUtils.COMPLETED_FLAG, DateTime.Now);
}
}
// Will this automatically overwrite the existing?
File.Delete(fileToUpdate);
File.WriteAllLines(fileToUpdate, fileContents);
}
catch (Exception ex)
{
RoboReporterConstsAndUtils.HandleException(ex);
}
}
So I do delete the file, but immediately replace it:
File.Delete(fileToUpdate);
File.WriteAllLines(fileToUpdate, fileContents);
The files being read have contents such as this:
Opas,20170110,20161127,20161231-COMPLETED 1/10/2017 12:33:27 AM
Opas,20170209,20170101,20170128-COMPLETED 2/9/2017 11:26:04 AM
Opas,20170309,20170129,20170225-COMPLETED
Opas,20170409,20170226,20170401
If "-COMPLETED" appears at the end of the record/row/line, it is ignored - will not be processed.
Also, if the second element (at index 1) is a date in the future, it will not be processed (yet).
So, for these examples shown above, the first three have already been done, and will be subsequently ignored. The fourth one will not be acted on until on or after April 9th, 2017 (at which time the data within the data range of the last two dates will be retrieved).
Why is the file sometimes deleted? What can I do to prevent it from ever happening?
If helpful, in more context, the logic is like so:
internal static string GenerateAndSaveDelPerfReports()
{
string allUnitsProcessed = String.Empty;
bool success = false;
try
{
List<String> delPerfRecords = ReadFileContents(DelPerfFile);
List<QueuedReports> qrList = new List<QueuedReports>();
foreach (string qrRecord in delPerfRecords)
{
var qr = ConvertCRVRecordToQueuedReport(qrRecord);
// Rows that have already been processed return null
if (null == qr) continue;
// If the report has not yet been run, and it is due, add i
to the list
if (qr.DateToGenerate <= DateTime.Today)
{
var unit = qr.Unit;
qrList.Add(qr);
MarkAsProcessed(DelPerfFile, qrRecord);
if (String.IsNullOrWhiteSpace(allUnitsProcessed))
{
allUnitsProcessed = unit;
}
else if (!allUnitsProcessed.Contains(unit))
{
allUnitsProcessed = allUnitsProcessed + " and "
unit;
}
}
}
foreach (QueuedReports qrs in qrList)
{
GenerateAndSaveDelPerfReport(qrs);
success = true;
}
}
catch
{
success = false;
}
if (success)
{
return String.Format("Delivery Performance report[s] generate
for {0} by RoboReporter2017", allUnitsProcessed);
}
return String.Empty;
}
How can I ironclad this code to prevent the files from being periodically trashed?
UPDATE
I can't really test this, because the problem occurs so infrequently, but I wonder if adding a "pause" between the File.Delete() and the File.WriteAllLines() would solve the problem?
UPDATE 2
I'm not absolutely sure what the answer to my question is, so I won't add this as an answer, but my guess is that the File.Delete() and File.WriteAllLines() were occurring too close together and so the delete was sometimes occurring on both the old and the new copy of the file.
If so, a pause between the two calls may have solved the problem 99.42% of the time, but from what I found here, it seems the File.Delete() is redundant/superfluous anyway, and so I tested with the File.Delete() commented out, and it worked fine; so, I'm just doing without that occasionally problematic call now. I expect that to solve the issue.
// Will this automatically overwrite the existing?
File.Delete(fileToUpdate);
File.WriteAllLines(fileToUpdate, fileContents);
I would simply add an extra parameter to WriteAllLines() (which could default to false) to tell the function to open the file in overwrite mode, and not call File.Delete() at all then.
Do you currently check the return value of the file open?
Update: ok, it looks like WriteAllLines() is a .Net Framework function and therefore cannot be changed, so I deleted this answer. However now this shows up in the comments, as a proposed solution on another forum:
"just use something like File.WriteAllText where if the file exists,
the data is just overwritten, if the file does not exist it will be
created."
And this was exactly what I meant (while thinking WriteAllLines() was a user defined function), because I've had similar problems in the past.
So, a solution like that could solve some tricky problems (instead of deleting/fast reopening, just overwriting the file) - also less work for the OS, and possibly less file/disk fragmentation.

Create/Open existing msg from path to new Outlook.MailItem in c#

Hello I'd like to create a Outlook.MailItem ( I believe ) from an existing one located on disk. I have the path stored in a string, and would like to access to save the body and attachments from it.
I can't seem to figure out how to open it in c# and access it.
currently I have something along the lines of
where fl evaluates out to something like "C:\users\msgs\email.msg"
Thanks for the time
Outlook.Application app = new Outlook.Application();
try
{
foreach (String fl in Directory.GetFiles(docInfo.LocalPath + _preprocessorDirectory))
{
if (Regex.IsMatch(fl.Trim(), _regex, RegexOptions.IgnoreCase))
{
Outlook.MailItem email = new Outlook.MailItem(fl);
SaveAttachments(email);
SaveBody(email);
}
}
}
catch (Exception ex)
{
logger.Error("Error in Process for document " + docInfo.OriginalPath, ex);
callback.Invoke(docInfo, false);
}
return false;
To open an item in outlook try:
var email = (Outlook.MailItem)app.Session.OpenSharedItem(fl)
From there, you can access the Attachments property and Body property as well.
Also, as I mentioned in my comment if the Regex.IsMatch is to determing the file extension, use Path.GetExtension() instead
I used this NuGet package: https://www.nuget.org/packages/MSGReader/
Seems to work fine. I prefer it to the MS OutlookApi library because it doesn't require Outlook to be installed.
I appreciate that it won't create instances of MailItem, as you have asked for in your question - but it will enable you to extract save the individual attachments and the body...

How do I prevent System.IO.Directory.Delete(pathtodelete, true) from giving me a "Directory is not empty" error?

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).

Categories

Resources