0

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 Answers1

0

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);
}
LZ_MSFT
  • 4,079
  • 1
  • 8
  • 9
  • I am not sure about SiteAssets. There is no warranty that this document library exists in every site that I am going to activate my feature. What is your idea? – hossein hashemian Nov 05 '19 at 18:13
  • We can only upload the file into "SiteAssets" in root web, and get file from the root web. Check my updated reply. – LZ_MSFT Nov 06 '19 at 02:29
  • You mean, we can be sure of existing "SiteAssets" document library in root web every site collection we are working on? – hossein hashemian Nov 06 '19 at 18:18
  • You can use PowerShell to check if this library in root web every site collection, – LZ_MSFT Nov 07 '19 at 01:50