Programmatically changing name of SPFolder - c#

I was wondering whether it is possible to programmatically change the name of an SPFolder after it has been created?
e.g.
foreach (SPFolder folder in list.RootFolder.SubFolders)
{
if (folder.Name.Equals("blah"))
{
// set the name of the folder to something else
folder.Name = "blah 2.0";
}
}
Googling so far suggested that MoveTo is the only way of doing so. There are a lot of items inside the folder so I'm reluctant to moving it unless there is absolutely no other ways.
Thanks.

I ended up using MoveTo as there was no other ways of doing this.

In a Document Library the field Name of an item (folder) has StaticName = FileLeafRef. So what really worked for me is
folder.Item[SPBuiltInFieldId.FileLeafRef] = "The new name";
folder.Item.Update();

when you have an SPFolder object, you can do it like this:
folder.item["Title"] = "blah 2.0";
folder.item.SystemUpdate();'

Related

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

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.

Environment.CurrentDirectory returns odd results

I have some issues with Environment.CurrentDirectory, it sometimes goes to the System32 folder. I looked online and found out why this happens and what alternatives I have (like Application.StartupPath and stuff like that) but the problem is the code is in a .dll that I am using and I can't edit it (or can I).
Is there anything I can do about this?
EDIT: In the duplicate issue the person writes their own dll. I don't own the dll I'm having problems with and I can't change it.
You can try to grab the path directly from the executable if CurrentDirectory is giving you an issue:
private void GetFilePath()
{
string filepath = string.Empty;
var processes = Process.GetProcessesByName("exe name");
foreach (var process in processes)
{
filepath = process.MainModule.FileName;
}
return filepath;
}

Find a root directory of the web application

I'm trying to find a root folder on the server. Nothing works, or works wrong
#{
string [] list = Directory.GetFiles(Directory.GetCurrentDirectory());
foreach(var item in list)
{
<p>#item</p>
}
}
Shows exactly what I don't need
#{
string [] list = Directory.GetFiles("~/");
foreach(var item in list)
{
<p>#item</p>
}
}
Doesn't work
How to solve this?
You can use the following:
Server.MapPath("~");
The ~ is always the root in an ASP.NET application. If you insert it in a Razor view it will be translated to the appropriate path for "external access", e.g. ~/Content/site.css will be converted to /Content/site.css if the site is hosted in the root directory or to e.g. /Page1/Content/site.css if it is hosted at a virtual directory called Page1. Therefor to get the absolute path you need to "map it".
If you do not have access to Server you can also use HostingEnvironment.ApplicationPhysicalPath.
Try
Server.MapPath("~");
or:
HostingEnvironment.ApplicationPhysicalPath
Refer http://msdn.microsoft.com/en-us/library/ms178116.aspx.
For your ease i have modified your code:
string [] list = Directory.GetFiles(Server.MapPath("~"));
StringBuilder sb=new StringBuilder();
foreach (var item in list)
{
sb.Append(item + "\n");
}
Response.Write(sb);
Even though I am giving you answer, I will suggest try to have path which is configurable in web.config or in the database because fixing paths are like hard coding the login ID :). Hope you got me.
Thanks

How to retrieve the Outlook folder of a mail item (Outlook.MailItem)?

I am getting my default inbox folder via inboxFolder = Globals.ThisAddIn.Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox
Elsewhere in my code, I begin doing a foreach loop to extract specific information I want from these MailItems
foreach (var item in this.inboxFolder.Items)
{
Outlook.MailItem mailItem = (Outlook.MailItem)item;
//.... doing stuff here
string SenderEmail = mailItem.SenderEmailAddress;
string SenderName = mailItem.SenderName;
string FolderLocation = mailItem.???; //how to retrieve folder location?
//.... more stuff here
}
For example: A user may have created a subfolder called 'Test' shown below.
Thank you for the pointer guys. However I was having some trouble implementing the same initially. Here is how I solved it, just in case if some one faces the same issue.
Outlook.MAPIFolder parentFolder = mailItemToDelete.Parent as Outlook.MAPIFolder;
string FolderLocation = parentFolder.FolderPath;
The Parent object is dynamic and hence was causing issue.
Do you mean folder path? Use MAPIFolder.FullFolderPath. Or MAPIFoldert.Name if you only need the name.
Also keep in mind that the value will be the same for all items in the folder, so there is no reason to evaluate it on each step of the loop.

directorynotfound exception

A DirectoryNotFound exception keeps happening for no apparent reason. The exception is thrown in:
public static string[] getKeywords(string filename)
{
string[] keywords = XElement.Load(filename).Elements("Keyword").Attributes("name").Select(n => n.Value).ToArray();
return keywords;
}
BUT it is called in this method:
public static void SyntaxHighlight(SyntaxHighlighter.SyntaxRichTextBox textbox, Language language)
{
switch (language)
{
case Language.Cmake:
textbox.Settings.Comment = "#";
string[] CmakeKeywords = getKeywords("APIs\\cmake.xml");
textbox.Settings.Keywords.AddRange(CmakeKeywords);
break;
case Language.CSharp:
textbox.Settings.Comment = "//";
string[] CSharpKeywords = getKeywords("APIs\\cs.xml");
textbox.Settings.Keywords.AddRange(CSharpKeywords);
break;
case Language.HTML:
textbox.Settings.Comment = "<!";
string[] HTMLKeywords = getKeywords("APIs\\html.xml");
textbox.Settings.Keywords.AddRange(HTMLKeywords);
break;
case Language.Python:
textbox.Settings.Comment = "#";
string[] PythonKeywords = getKeywords("APIs\\python.xml");
textbox.Settings.Keywords.AddRange(PythonKeywords);
break;
}
}
UPDATE:
I have a folder in my project called APIs. I checked the file names several times. Here is the exception: Could not find a part of the path 'C:\Users\Mohit\Documents\Visual Studio 2010\Projects\Notepad\Notepad\bin\Debug\APIs\cs.xml'. Thats the EXACT path of the file!
There's little hope of your program ever finding that folder. When you deploy your app, there is no project folder. The best way to organize it is to add the .xml files to your project with Project + Add Existing. Select them in Solution Explorer and in the Properties window set Build action = None and Copy to Output Directory = Copy if Newer. Build. That puts the files in the same directory as your .exe.
Find them back at runtime with System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)
You might have better luck a fully qualified URL (eg #"D:\mypage\APIs\html.xml")
Looks like you are assuming the current directory is the install directory? You should find the directory like...
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) +
Environment.DirectorySeparatorChar +
"file you are looking for".
Are you sure your working directory is the right one? Try to print the absolute path of the . directory. Also, list it's contents and see if that directory really is there.
I'd recommend changing your getKeywords method to be something like this to aid debugging
public static string[] getKeywords(string filename)
{
var file = new FileInfo(filename);
if (!file.Exists)
{
throw new FileNotFoundException("The requested file was not found: " + file.FullName);
}
string[] keywords = XElement.Load(filename).Elements("Keyword").Attributes("name").Select(n => n.Value).ToArray();
return keywords;
}
This should give you the full path at which it was attempting to load the file, which should make the problematic path clear to you.
I tried #nobugz method and it worked. Once you set the properties of each *.xml file to:
The best way to organize it is to add the .xml files to your project with Project + Add Existing. Select them in Solution Explorer and in the Properties window set Build action = None and Copy to Output Directory = Copy if Newer. Build. That puts the files in the same directory as your .exe.
Then put this to get your path for each case in your switch case replacing "filename" with each filename you have.
string[] YourVar = getKeywords(string.Format("{0}\\APIs\\filename.xml", Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)));

Categories

Resources