Thursday, March 02, 2006

WSS : Security Exception when Upload File using WSS SDK

I keep hitting an exception when I use the WSS SDK to upload a document to a document library in my WSS app. The error message read
The security validation for this page is invalid.
Click Back in your Web browser, refresh the page,
and try your operation again.


After some googling, the solution is you have to set the AllowUnsafeUpdates property of SPSite and SPWeb object to true before you upload the file. The code look like this:

using System.IO;

private void btnUpload_Click(object sender, System.EventArgs e)
{
string targetSite = "http://wssserver/sites/myteamsite";
string docLib = "my doc lib";
byte[] contents = null;

string saveAsFile = Path.GetFileName(FileUpload.PostedFile.FileName);
Stream stream = FileUpload.PostedFile.InputStream;

contents = new byte[(int)stream.Length];
stream.Read(contents, 0, (int)stream.Length);
stream.Close();

SPSite site = new SPSite(targetSite);
SPWeb web = site.OpenWeb();

site.AllowUnsafeUpdates = true;
web.AllowUnsafeUpdates = true;

SPFolder folder = web.Folders[docLib];

folder.Files.Add(saveAsFile, contents, true);

site.AllowUnsafeUpdates = false;
web.AllowUnsafeUpdates = false;

web.Close();
site.Close();
}

Labels:

1 Comments:

At 6:57 PM, Blogger Babu said...

Thanks! I was also trying to achieve the same for last two days. Got it! its working fine

 

Post a Comment

<< Home