get file in featureActivated encounter an error : “Value does not fall within the expected range”

170 views Asked by At

I set to copy a text file from a module to SharePoint server directory

<?xml version="1.0" encoding="utf-8"?>
 <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
   <Module Name="MyModule">
    <File IgnoreIfAlreadyExists="TRUE" Path="MyModule\newFile.txt" Url="MyModule/newFile.txt" />
  </Module>
</Elements>

After that, in featureActivated, I am going to get the file by this code:

                try
                {
                    SPFile newFile = myWeb.GetFile(properties.Definition.RootDirectory + "\\MyModule\\newFile.txt");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

I got this exception : “Value does not fall within the expected range”. What is wrong with me?

1

There are 1 answers

4
LZ_MSFT On

The SPWeb.GetFile Method (String) get file from SharePoint site, the properties.Definition.RootDirectory return the local path, you will get the exception.

I suggest you upload the file into document library like "Site Assets" in root web, then get file in feature receiver.

Example code:

Elements.xml

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="MyModule" Url="SiteAssets" RootWebOnly="TRUE">
    <File IgnoreIfAlreadyExists="TRUE" Type="GhostableInLibrary" Path="MyModule\newFile.txt" Url="newFile.txt" />
  </Module>
</Elements>

Feature Receiver

try
{
    SPWeb myWeb = SPContext.Current.Site.RootWeb;
    SPFile newFile = myWeb.GetFile(myWeb.ServerRelativeUrl + "/SiteAssets/newFile.txt");
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}