Sie sind auf Seite 1von 10

How to: Access, Copy, and Move Files

You can use the GetFolder method of the SPWeb class to return a specified folder and then access
individual files in the folder. After instantiating an SPWeb object (for example, as mySite), use
SPFolder myFolder = mySite.GetFolder("Shared Documents") (in Visual Basic 2005,
use Dim myFolder As SPFolder = mySite.GetFolder("Shared Documents")) to
return the Shared Documents folder for the site.

Example
The following example returns the collection of files in the folder and displays information about the files.
Visual Basic
Copy Code

Dim myFiles As SPFileCollection = myFolder.Files


Dim file As SPFile
For Each file In

myFiles

Response.Write(file.Url.ToString() & "<BR>")


Response.Write(file.Length.ToString() & "<BR>")
Next file
C#
Copy Code

SPFileCollection myFiles = myFolder.Files;


foreach (SPFile file in myFiles)
{
Response.Write(file.Url.ToString() + "<BR>");
Response.Write(file.Length.ToString() + "<BR>");
}
The previous example lists the URL and size of every file within the folder.
The example requires using directives (Imports in Visual Basic) for the Microsoft.SharePoint
namespace.
To copy files from one location to another, use one of the CopyTo methods of the SPFile class. In the
following example, the Page_Load event handler instantiates an SPWeb object for the current site
context. The Click event handler iterates through all the files in the folder, listing the name and size (in
kilobytes) of each file that exceeds a multiple of the value specified by the user in a text box, and
copying the file to a folder named Archive.
Visual Basic
Copy Code

Private mySite As SPWeb


Private Sub Page_Load(sender As Object, e As System.EventArgs)
mySite = SPControl.GetContextWeb(Context)

End Sub 'Page_Load


Private Sub Button1_Click(sender As Object, e As System.EventArgs)
Dim
Dim
Dim
Dim

maxSize As Integer = Convert.ToInt32(TextBox1.Text)


myFolder As SPFolder = mySite.GetFolder("Shared Documents")
myFiles As SPFileCollection = myFolder.Files
file As SPFile

For Each file In

myFiles

If file.Length > maxSize * 1024 Then


Response.Write(SPEncode.HtmlEncode(file.Name) & " :: "
& file.Length / 1024 & "kb<BR>")
file.CopyTo("Archive/" & file.Name, True)
End If
Next file
End Sub 'Button1_Click
C#
Copy Code

private SPWeb mySite;


private void Page_Load(object sender, System.EventArgs e)
{
mySite = SPControl.GetContextWeb(Context);
}
private void Button1_Click(object sender, System.EventArgs e)
{
int maxSize = Convert.ToInt32(TextBox1.Text);
SPFolder myFolder = mySite.GetFolder("Shared Documents");
SPFileCollection myFiles = myFolder.Files;
foreach (SPFile file in myFiles)
{
if (file.Length>(maxSize*1024))
{
Response.Write(SPEncode.HtmlEncode(file.Name) + ": "
+ file.Length/1024 + "kb<BR>");
file.CopyTo("Archive/" + file.Name, true);
}
}

}
In the example, the CopyTo method uses two parameters, one that specifies the destination URL for the
copied file, and the other a Boolean value that specifies whether to overwrite any file of the same name
that is located at the destination.
The previous example requires using directives (Imports in Visual Basic) for the
Microsoft.SharePoint, Microsoft.SharePoint.Utilities, and Microsoft.SharePoint.WebControls
namespaces.
The following example moves all files from the Shared Documents list of the current site to another
folder named StorageFolder, overwriting any file of the same name that may be located there.
Visual Basic
Copy Code

Dim
Dim
Dim
Dim

mySite As SPWeb = SPControl.GetContextWeb(Context)


myFolder As SPFolder = mySite.GetFolder("Shared Documents")
myFiles As SPFileCollection = myFolder.Files
i As Integer

For i = myFiles.Count - 1 To 0 Step -1


myFiles(i).MoveTo("StorageFolder/" & myFiles(i).Name, True)
Next i
C#
Copy Code

SPWeb mySite = SPControl.GetContextWeb(Context);


SPFolder myFolder = mySite.GetFolder("Shared Documents");
SPFileCollection myFiles = myFolder.Files;
for (int i = myFiles.Count - 1; i > -1; i--)
{
myFiles[i].MoveTo("StorageFolder/" + myFiles[i].Name, true);
}
As the example illustrates, when collections are modified in the course of code execution by deleting or
moving items, the counter for iterating through the collection must decrease in value with each iteration.
The previous example requires using directives (Imports in Visual Basic) for the
Microsoft.SharePoint and Microsoft.SharePoint.WebControls namespaces.

How to: Upload a File to a SharePoint Site from a Local


Folder
This programming task shows how to upload a file from a local folder to a folder on a Windows
SharePoint Services site. The task uses the EnsureParentFolder method to ensure that the destination
folder exists.

Procedures
To upload a file to a folder on a SharePoint site from a local folder
1. Create a Web application in Visual Studio 2005 as described in How to: Create a Web
Application in a SharePoint Web Site, adding a FormDigest control and a page directive for the
Microsoft.SharePoint.WebControls namespace to the .aspx file, as follows:

Copy Code

<%@ Register Tagprefix="SharePoint"


Namespace="Microsoft.SharePoint.WebControls"
Assembly="Microsoft.SharePoint, Version=12.0.0.0,
Culture=neutral,
PublicKeyToken=71e9bce111e9429c" %>
Note:
You can obtain the PublicKeyToken value for the current Windows SharePoint Services deployment
from the default.aspx file in the Local_Drive:\Program Files\Common

Files\Microsoft Shared\Web Server


Extensions\12\TEMPLATE\SiteTemplates\sts folder, or from information provided for
the Microsoft.SharePoint assembly at Local_Drive:\%WINDOWS%\assembly in Windows
Explorer.
2.

Add an HtmlInputFile control, a text box, and a button to the form on the .aspx page:

Copy Code

<form id="Form1" method="post" runat="server">


<SharePoint:FormDigest runat="server" />
<input id="File1" type="file" runat="server"
title="upldFileBox">
<asp:Button id="Button1" runat="server"
Text="Upload File"></asp:Button>
<asp:TextBox id="TextBox1" runat="server"></asp:TextBox>

</form>
3.

In the .aspx.cs code-behind file, add using directives for the System.IO and
Microsoft.SharePoint namespaces, as follows:
Visual Basic

Copy Code

Imports System.IO
Imports Microsoft.SharePoint
C#

Copy Code

using System.IO;
using Microsoft.SharePoint;
4.

Add the following code to the Click event for the button:
Visual Basic

Copy Code

If File1.PostedFile Is Nothing Then


Return
End If
Dim destUrl As String = TextBox1.Text
Dim site As SPWeb = New SPSite(destUrl).OpenWeb()
Dim fStream As Stream = File1.PostedFile.InputStream
Dim contents(fStream.Length) As Byte
fStream.Read(contents, 0, CInt(fStream.Length))

fStream.Close()
EnsureParentFolder(site, destUrl)
site.Files.Add(destUrl, contents)
C#

Copy Code

if (File1.PostedFile == null)
return;
string destUrl = TextBox1.Text;
SPWeb site = new SPSite(destUrl).OpenWeb();
Stream fStream = File1.PostedFile.InputStream;
byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();
EnsureParentFolder(site, destUrl);
site.Files.Add(destUrl, contents);
The value that you type in the text box for the destination must be an absolute URL, including
the file name, which is assigned to the destUrl parameter.
In addition to instantiating an SPWeb object for the parent site, the combined use of the SPSite
constructor and OpenWeb method validates the URL and throws an argument exception if the
URL is not served by the current Windows SharePoint Services deployment. A
System.Web.UI.HtmlControls.HtmlInputFile object is used to read the source file into a
byte array for use with the Add method of the SPFileCollection class.
5.

The EnsureParentFolder method ensures that the parent folder in the destination URL exists
in the specified site, and it returns the site-relative URL of the parent folder. The
EnsureParentFolder method accepts two parameters: an SPWeb object that represents the

parent site, and a string that contains the absolute URL that is passed from the UploadFile
method. If the parent folder does not exist, the EnsureParentFolder method creates it.
Visual Basic

Copy Code

Public Function EnsureParentFolder(parentSite As SPWeb,


destinUrl As String) As String
destinUrl = parentSite.GetFile(destinUrl).Url
Dim index As Integer = destinUrl.LastIndexOf("/")
Dim parentFolderUrl As String = String.Empty
If index > - 1 Then
parentFolderUrl = destinUrl.Substring(0, index)
Dim parentFolder As SPFolder
= parentSite.GetFolder(parentFolderUrl)
If Not parentFolder.Exists Then
Dim currentFolder As SPFolder =
parentSite.RootFolder
Dim folder As String
For Each folder In

parentFolderUrl.Split("/"c)

currentFolder =
currentFolder.SubFolders.Add(folder)
Next folder
End If
End If
Return parentFolderUrl
End Function 'EnsureParentFolder
C#

Copy Code

public string EnsureParentFolder(SPWeb parentSite, string


destinUrl)
{
destinUrl = parentSite.GetFile(destinUrl).Url;
int index = destinUrl.LastIndexOf("/");
string parentFolderUrl = string.Empty;
if (index > -1)
{
parentFolderUrl = destinUrl.Substring(0, index);
SPFolder parentFolder
= parentSite.GetFolder(parentFolderUrl);
if (! parentFolder.Exists)
{
SPFolder currentFolder = parentSite.RootFolder;
foreach(string folder in parentFolderUrl.Split('/'))
{
currentFolder
= currentFolder.SubFolders.Add(folder);
}
}
}
return parentFolderUrl;
}
6.

The GetFile method of the SPWeb class is used in combination with the Url property of the
SPFile class to convert the URL to a site-relative URL, throwing an exception if the specified URL
is not found within the scope of the site. The URL of the parent folder is calculated by using the
String.LastIndexOf method to determine the last appearance of a forward slash (/) within the
destination URL. If there is no slash (in other words, the index equals -1), then the destination
is the root folder for the site and the parentFolderUrl parameter returns an empty string.

Otherwise, the example uses the GetFolder method of the SPWeb class to return the
destination parent folder. If the folder does not exist, the example constructs the folder.
To upload a file from a local folder on the same server that is running Windows SharePoint Services, you
can use a System.IO.FileStream object instead. In this case, add a using directive for the System.IO
namespace, in addition to directives for System and Microsoft.SharePoint. The following example
uses the Click event handler to call an UploadFile method, which in turn calls the previously described
EnsureParentFolder method.
Visual Basic
Copy Code

Public Sub UploadFile(srcUrl As String, destUrl As String)


If Not File.Exists(srcUrl) Then
Throw New ArgumentException(String.Format("{0} does not
exist",
srcUrl), "srcUrl")
End If
Dim site As SPWeb = New SPSite(destUrl).OpenWeb()
Dim fStream As FileStream = File.OpenRead(srcUrl)
Dim contents(fStream.Length) As Byte
fStream.Read(contents, 0, CInt(fStream.Length))
fStream.Close()
EnsureParentFolder(site, destUrl)
site.Files.Add(destUrl, contents)
End Sub 'UploadFile
C#
Copy Code

public void UploadFile(string srcUrl, string destUrl)


{
if (! File.Exists(srcUrl))
{
throw new ArgumentException(String.Format("{0} does not
exist",
srcUrl), "srcUrl");
}
SPWeb site = new SPSite(destUrl).OpenWeb();
FileStream fStream = File.OpenRead(srcUrl);
byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();

EnsureParentFolder(site, destUrl);
site.Files.Add(destUrl, contents);
}
The UploadFile method accepts two parameters. The srcUrl parameter specifies the path of the source
location in the file system of the local computer, and the destUrl parameter specifies the absolute URL of
the destination. A System.IO.FileStream object is used to read the source file into a byte array for use
with the Add method of the SPFileCollection class.

Das könnte Ihnen auch gefallen