I'm trying to save file from network location to SharePoint document library.
This is code of my method:
//parameters: string documentLibraryUrl, string filePath
FileInfo fi = new FileInfo(filePath);
string fileName = fi.Name.Trim();
using (SPSite oSite = new SPSite(documentLibraryUrl))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
SPFolder myLibrary = oWeb.GetFolder(documentLibraryUrl);
// Prepare to upload
using (FileStream fileStream = File.OpenRead(filePath))
{
// Upload document
SPFile spFile = oWeb.GetFile(myLibrary.Url + "/" + fileName);
filePathInLibrary = spFile.ParentFolder.ServerRelativeUrl + "/" + fileName;
spFile.SaveBinary(fileStream); //this line throws exception
// Commit
myLibrary.Update();
}
}
}
When I call SPFile.SaveBinary
, I get following DirectoryNotFoundException
:
<nativehr>0x80070003</nativehr><nativestack></nativestack>There is no file with URL "http://localhost:9999/Lists/Documents/testfile.pdf" in this Website.
The fileStream
variable is not null and has Length > 0. The list exists.
What could be wrong?
So after Amit's reply, I changed the code from line:
spFile.SaveBinary(fileStream);
to this block:
if (spFile.Exists)
{
//do some logging here
}
else
{
spFile = myLibrary.Files.Add(myLibrary.Url + "/" + fileName, fileStream);
}
In fact I get exactly the same error message on myLibrary.Files.Add
.
What else could be the reason of this error? The code is probably correct, because it worked on different server. I'm thinking about permissions - can it be, that I need extra permissions on SharePoint or on SQL server?
I'm able to add file to the list in UI (in browser) without problems. I'm using Claims Based Authentication. My user (with Windows identity) has Full Control permissions on Web Application.
if (spFile.Exists)
should not be used / depended upon for an existence check if you useSPWeb.GetFile()
as the results of this property are inconsistent at best: blog.mastykarz.nl/inconvenient-spwebgetfilestringSPWeb.GetFile
and the file definitely exists. Any luck on resolving?