I am trying to read all the calendars I have in my outlook with C#, but i have a problem getting access to the ones I create inside outlook (right click -> new calendar).
I'm trying to get them by:
Outlook.Application app = new Outlook.Application();
Outlook.NameSpace ns = app.GetNamespace("MAPI");
Outlook.MAPIFolder folderss = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar);
or by:
Application.Session.Stores
but none of them holds my new calendar.
do you have an Idea how to reach them?
Calendars are just Folders with DefaultItemType OlItemType.olAppointmentItem.
They can be created in any of the Outlook Stores on any level of the Folder hierarchy.
Assuming that the calendar was created in the root folder of one of your Stores, the following C# code will find it:
void findMyCalendar(String name)
{
string path = null;
Outlook.Application app = new Outlook.Application();
Outlook.NameSpace ns = app.GetNamespace("MAPI");
// there may be more than one Store
// each .ost and .pst file is a Store
Outlook.Folders folders = ns.Folders;
foreach (Outlook.Folder folder in folders)
{
Outlook.MAPIFolder root = folder;
path = findCalendar(root, name);
if (path != null)
{
break;
}
}
MessageBox.Show(path ?? "not found!");
}
// non-recursive search for just one level
public string findCalendar(MAPIFolder root, string name)
{
string path = null;
foreach (Outlook.MAPIFolder folder in root.Folders)
{
if (folder.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase) &&
(folder.DefaultItemType == OlItemType.olAppointmentItem))
{
path = folder.FolderPath;
break;
}
}
return path;
}
Related
I am trying to create a new folder within a document library. Actually, the code works well, but when the title of the new folder starts with a blank, I get an exception "File not found" and the folder is not created.
I already tried to encode the title: replaced the blach by "%20" and by "+". In this case the folder is created, but it contains other characters like"+" at the first position in the title.
I tried to create the folder " blankBefore" in the SharePoint application by using the browser - and it works. The folder is create and looks like this " blankBefore".
I can create folders with a blank in the title, but not, if the title of the folder starts with a blank.
public bool CreateFolder(SharePointNode spParentNode, string strFolderName)
{
ClientContext localCTX = new ClientContext(spParentNode.ParentSite);
ConectClient(localCTX);
Folder newFolder = null;
var folder = localCTX.Web.GetFolderByServerRelativeUrl(spParentNode.URL);
localCTX.Load(folder);
localCTX.Load(folder.Folders);
Folder newFolder = folder.Folders.Add(strFolderName);
newFolder.Update();
localCTX.ExecuteQuery();
return true;
}
Create folder in SharePoint list (SharePoint 2010, 2013, 2016)
using (var clientContext = new ClientContext("http://sp/sites/test"))
{
string folderName = "test";
var list = clientContext.Web.Lists.GetByTitle("ListBase");
list.EnableFolderCreation = true;
clientContext.Load(list);
clientContext.Load(list.RootFolder);
clientContext.Load(list.RootFolder.Folders);
clientContext.ExecuteQuery();
var folderCollection = list.RootFolder.Folders;
foreach (var folder in folderCollection)
{
if (folder.Name == folderName)
{
clientContext.Load(folder.Files);
clientContext.ExecuteQuery();
}
else
{
var itemCreateInfo = new ListItemCreationInformation
{
UnderlyingObjectType = FileSystemObjectType.Folder,
LeafName = folderName
};
var newItem = list.AddItem(itemCreateInfo);
newItem["Title"] = folderName;
newItem.Update();
clientContext.ExecuteQuery();
break;
}
}
}
I am trying to read the emails that are being moved to the clutter folder by outlook. The below code works fine for other folders, but when I try to open the clutter folder the code defaults to the error message indicate the folder does not exist.
oApp = new Microsoft.Office.Interop.Outlook.Application();
oNS = (Microsoft.Office.Interop.Outlook._NameSpace)oApp.GetNamespace("MAPI");
oNS.Logon(null, null, false, false);
oFolder = oNS.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
string folderName = "Clutter";
try
{
oSubfolder = oFolder.Folders[folderName];
for (int i = 1; i <= oSubfolder.Items.Count; i++)
{
item = (Microsoft.Office.Interop.Outlook.PostItem)oFolder.Items[i];
}
}
catch
{
MessageBox.Show("There is no folder named " + folderName +
".", "Find Folder Name");
}
You are assuming Clutter is the child of the Inbox folder. It is Inbox's peer:
oFolder = (Outlook.MAPIFolder)oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox).Parent;
I'm trying to create a tree view to search for a directories in a remote server using FTP/SFTP connections, What I'm trying to do is start filling the tree view with all the available directories starting with the home directory such as the following example:
Home---->SubFolder
|
|---->Another Folder
|
|---->MyOtherFolder
Then when the user start clicking in each folder it start to display their subdirectories from the tree view as the follwoing example (clicking in Another Folder):
Home ---->SubFolder
|
|---->Another Folder -------> MyFolder1
| | -------> MyFolder2
|
|---->MyOtherFolder
I'm trying to get those folders but it's throwing an exception, also it is gathering files, not folders....
this is the code that I have....
private void FillTree()
{
SessionOptions SessionOptions = new SessionOptions();
Session MySession = new Session();
SessionOptions.HostName = InterfaceValues[0];
SessionOptions.UserName = InterfaceValues[2];
SessionOptions.Password = InterfaceValues[3];
SessionOptions.PortNumber = Convert.ToInt32(InterfaceValues[1]);
if (string.Compare(InterfaceValues[9], "FTP", true) == 0)
SessionOptions.Protocol = WinSCP.Protocol.Ftp;
else if (string.Compare(InterfaceValues[9], "SFTP", true) == 0)
{
SessionOptions.Protocol = WinSCP.Protocol.Sftp;
SessionOptions.SshPrivateKeyPath = InterfaceValues[12];
SessionOptions.SshHostKeyFingerprint = InterfaceValues[10];
}
try
{
MySession.Open(SessionOptions);
foreach (RemoteFileInfo info in MySession.EnumerateRemoteFiles("/", "*", EnumerationOptions.AllDirectories))
{
if (info.IsDirectory)
tvRemoteDirectory.Nodes.Add(info.Name);
}
MySession.Close();
}
catch (Exception ex)
{
MySession.Close();
MessageBox.Show("Not possible to connect to " + InterfaceValues[0] + "\nError Message: " + ex.Message);
this.Close();
}
The exception that I'm getting is:
{WinSCP.SessionRemoteException: Error listing directory '/jpm_icl'. ---> WinSCP.SessionRemoteException: Permission denied.
Error code: 3
Error message from server: Permission Denied!
Any idea what could I do at this point?
What I did was this:
ListDirectory function to retrieve all the directories, as I don't want the directory "." and "." I have to exclude it.
RemoteDirectoryInfo RemoteDirectory;
if (RemoteDirectoryPath != "Home")
RemoteDirectory = MySession.ListDirectory(RemoteDirectoryPath);
else
RemoteDirectory = MySession.ListDirectory("/");
if (tvRemoteDirectory.SelectedNode.Nodes.Count > 0) tvRemoteDirectory.SelectedNode.Nodes.Clear();
foreach (RemoteFileInfo fileinfo in RemoteDirectory.Files)
{
if (fileinfo.IsDirectory)
{
if (fileinfo.Name != "." &&
fileinfo.Name != "..")
{
TreeNode ChildNode = new TreeNode();
ChildNode.Text = fileinfo.Name;
ChildNode.ImageIndex = 0;
tvRemoteDirectory.SelectedNode.Nodes.Add(ChildNode);
tvRemoteDirectory.ExpandAll();
}
}
}
since a few days I'm trying to rename the sent mail folder, deleted elements and the inbox folder via c#.
I've tryed something like this:
List<Outlook.MailItem> mailItems = new List<Outlook.MailItem>();
Outlook.Application app = new Outlook.Application();
Outlook.NameSpace outlookNs = app.GetNamespace("MAPI");
// Add PST file (Outlook Data File) to Default Profile
outlookNs.AddStore(pstFilePath);
Outlook.MAPIFolder rootFolder = outlookNs.Stores[pstName].GetRootFolder();
Outlook.Folders subFolders = rootFolder.Folders;
foreach (Outlook.Folder folder in subFolders)
{
folder.Name = (folder.Name == "deleted Elements"?"deleted":folder.Name);
}
But without success. I always get the exceptiion that I do not have permissions to change the name. Other custom created folders I'm able to rename without any problems.
Is there something to do to unlock the folder?
Or is there an other possibility to access the folders?
Thanks a lot
Edit: The Expetion is: You do not have permissions.
public string RenameFolder(string name, string folderid)
{
Outlook.Application app = new Outlook.Application();
Outlook.NameSpace ns = null;
Outlook.Folder folder = null;
string n= null;
try
{
ns = app.GetNamespace("MAPI");
folder = ns.GetFolderFromID(folderid) as Outlook.Folder;
n=folder.Name;
folder.Name = (folder.Name = name) ;
return n + " has been successfully changed to " + folder.Name;
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
if (app != null)
{
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(app);
}
if (folder != null)
{
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(folder);
}
if (ns != null)
{
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(ns);
}
}
}
this code is working for me..when i run visual studio in administator mode..
How do you get the directory target of a shortcut folder? I've search everywhere and only finds target of shortcut file.
I think you will need to use COM and add a reference to "Microsoft Shell Control And Automation", as described in this blog post:
Here's an example using the code provided there:
namespace Shortcut
{
using System;
using System.Diagnostics;
using System.IO;
using Shell32;
class Program
{
public static string GetShortcutTargetFile(string shortcutFilename)
{
string pathOnly = System.IO.Path.GetDirectoryName(shortcutFilename);
string filenameOnly = System.IO.Path.GetFileName(shortcutFilename);
Shell shell = new Shell();
Folder folder = shell.NameSpace(pathOnly);
FolderItem folderItem = folder.ParseName(filenameOnly);
if (folderItem != null)
{
Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
return link.Path;
}
return string.Empty;
}
static void Main(string[] args)
{
const string path = #"C:\link to foobar.lnk";
Console.WriteLine(GetShortcutTargetFile(path));
}
}
}
In windows 10 it needs to be done like this, first add COM reference to "Microsoft Shell Control And Automation"
// new way for windows 10
string targetname;
string pathOnly = System.IO.Path.GetDirectoryName(LnkFileName);
string filenameOnly = System.IO.Path.GetFileName(LnkFileName);
Shell shell = new Shell();
Shell32.Folder folder = shell.NameSpace(pathOnly);
FolderItem folderItem = folder.ParseName(filenameOnly);
if (folderItem != null) {
Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
targetname = link.Target.Path; // <-- main difference
if (targetname.StartsWith("{")) { // it is prefixed with {54A35DE2-guid-for-program-files-x86-QZ32BP4}
int endguid = targetname.IndexOf("}");
if (endguid > 0) {
targetname = "C:\\program files (x86)" + targetname.Substring(endguid + 1);
}
}
If you don't want to use dependencies you can use https://blez.wordpress.com/2013/02/18/get-file-shortcuts-target-with-c/
But lnk format is undocumented, so do it only if you understand risks.
An even simpler way to get the linked path that I use is:
private static string LnkToFile(string fileLink)
{
string link = File.ReadAllText(fileLink);
int i1 = link.IndexOf("DATA\0");
if (i1 < 0)
return null;
i1 += 5;
int i2 = link.IndexOf("\0", i1);
if (i2 < 0)
return link.Substring(i1);
else
return link.Substring(i1, i2 - i1);
}
But it will of course break if the lnk-file format changes.
public static string GetLnkTarget(string lnkPath)
{
var shl = new Shell();
var dir = shl.NameSpace(Path.GetDirectoryName(lnkPath));
var itm = dir.Items().Item(Path.GetFileName(lnkPath));
var lnk = (ShellLinkObject)itm.GetLink;
if (!File.Exists(lnk.Path)){
return lnk.Path.Replace("Program Files (x86)", "Program Files");
}
else{
return lnk.Path;
}
}
if you want find your application path that has shortcut on desktop, an easy way that i use, is the following:
Process.GetCurrentProcess().MainModule.FileName.Substring(0, Process.GetCurrentProcess().MainModule.FileName.LastIndexOf("\\")
this code return any exe path that is running,Regardless that who requested file
Thanks to Mohsen.Sharify's answer I got more neat piece of code:
var fileName = Process.GetCurrentProcess().MainModule.FileName;
var folderName = Path.Combine(fileName, ".."); //origin folder
All file shortcuts have a .lnk file extension you can check for. Using a string for example, you could use string.EndsWith(".lnk") as a filter.
All URL shortcuts have a .url file extension, so you will need to account for those as well if needed.