Here is the setup. On error i want to write (append) the error message to an SPFile in a document library. If the file doesn't already exist i want to create it. Searching around this is what i came up with. However, when it attempts to create the file using SPFolder.Files.Add it throws an I/O Error exception (no inner exception/better description during debug). If the file is already there, however, all is well and the file is updated as expected. So first question would be what am i doing wrong. Second would be is there a better way to do what i am doing (no doubt there is).....any help appreciated
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
UnicodeEncoding uniEncoding = new UnicodeEncoding();
StringBuilder errors = new StringBuilder();
foreach (Exception e in cc.aggregatedException.m_InnerExceptionsList)
{
errors.Append(e.Message + Environment.NewLine);
}
SPFile logFile = csvList.Items.Cast<SPListItem>()
.Where(x => x.Name.Equals(logFileName))
.Select(x => x.File)
.FirstOrDefault();
if (logFile == null)
{
using (MemoryStream ms = new MemoryStream())
{
using (StreamWriter sw = new StreamWriter(ms, uniEncoding))
{
sw.Write(errors.ToString());
}
SPFolder csvLibraryFolder = SPContext.Current.Web.Folders[libraryName];
csvLibraryFolder.Files.Add(logFileName, ms, false);
}
}
else
{
byte[] fileContents = logFile.OpenBinary();
string newContents = enc.GetString(fileContents) +
Environment.NewLine + errors.ToString();
logFile.SaveBinary(enc.GetBytes(newContents));
}