add a line to SPFile object - c#

I simply want to add a line to an SPFile object, which is a simple txt file.
Is there a simple way to do this ? I was thinking
Thanks
EDIT : that's what i have for the moment :
public static void addLine(SPFile file, string line)
{
using(System.IO.StreamWriter strWriter = new System.IO.StreamWriter(file.OpenBinaryStream())){
strWriter.WriteLine(line);
}
}
I don't have any error here, but the file doesn't get saved. I've tried to do something like :
file.SaveBinary( args )
But i don't know what to put in args.
If you can help me.
Thanks

You need SPFile.OpenBinaryStream, one of SPFile.SaveBinary to read/write. Some string manipulation of TextReader created over resulting stream like TextReader.ReadToEnd and write resulting data to MemoryStream with TextWriter.
Warning: non-compiled code below:
using (var readStream = file.OpenBinaryStream())
{
using(var reader = new StreamReader(readStream)
{
var allText = reader.ReadToEnd();
var writeStream = new MemoryStream();
using(var writer = new TextWriter(writeStream))
{
writer.Write(allText);
writer.Write(extraText);
}
file.SaveBinary(writeStream.ToArray();
}
}

Related

ASP.NET (Blazor Server) How to Export CSV File (CSV created by CsvHelper)

I want to export a csv file, which are made by CsvHelper.
I searched already for a solution but to be honest i didnt get it.
This is my Code
private async Task GetExcel()
{
var controller = new DownloadController();
controller.DownloadFileMandantProvisioning(filteredResult)
}
Controller:
public IActionResult DownloadFileMandantProvisioning(IEnumerable<ScopeMandantProvisioningModel> list)
{
var config = new CsvConfiguration(CultureInfo.CurrentCulture) { Delimiter = ";", Encoding = Encoding.UTF8 };
var memoryStream = new MemoryStream();
using (var writer = new StreamWriter(memoryStream, leaveOpen: true))
{
using (var csv = new CsvWriter(writer, config))
{
csv.WriteRecords(list);
}
}
memoryStream.Seek(0, SeekOrigin.Begin);
return File(memoryStream, "text/csv", "MandantProvisioning.csv");
}
I dont unterstand at which moment the file should be downloaded? If i hit de button which calls the functionn nothing happens. I hope you can help me. Thank you very much :)
I tried something like this but with CsvHelper.
I whatch this Video too, but didn't get it.
After Debugging i saw that i have a Read and Write Timeouts, but it didn't throw an exception or soemthing. Nothing happens.

Exception when writing data with CsvHelper

I'm trying to write data to a CSV-file using CsvHelper. However, I always get the following exception:
CsvHelper.Configuration.ConfigurationException: "Types that inherit
IEnumerable cannot be auto mapped. Did you accidentally call GetRecord
or WriteRecord which acts on a single record instead of calling
GetRecords or WriteRecords which acts on a list of records?"
This is my code (C#):
TextWriter outfile = new StreamWriter("blatest.csv");
List<string> test = new List<string>
{
"hello",
"world"
};
CsvWriter csv = new CsvWriter(outfile);
csv.WriteRecords(test);
I would like to write a List<string> or (ideally) a List<Dictionary<string, string>> to CSV. What would be the correct code for this? And how can I set the header row?
Any help is appreciated. I really can't wrap my head around this.
For the error, it is because string implements IEnumerable (because it is char[]). Generally using WriteRecords you pass in an IEnumerable of custom objects.
You could try another way (Example)
using(var stream = new MemoryStream())
using(var reader = new StreamReader(stream))
using(var writer = new StreamWriter(stream))
using(var csvWriter = new CsvHelper.CsvWriter(writer))
{
//csvWriter.Configuration.HasHeaderRecord = false;
foreach( var s in test)
{
csvWriter.WriteField(s);
}
writer.Flush();
stream.Position = 0;
reader.ReadToEnd(); //dump it where you want
}

Issue in create and write in a text file using c#

I try to create a text file and write some data to it. I am using the following code:
public void AddNews(string path,string News_Title,string New_Desc)
{
FileStream fs = null;
string fileloc = path + News_Title+".txt";
if (!File.Exists(fileloc))
{
using (fs = new FileStream(fileloc,FileMode.OpenOrCreate,FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(fileloc))
{
sw.Write(New_Desc);
}
}
}
}
I got this exception in stream writer:
The process cannot access the file '..............\Pro\Content\News\AllNews\Par.txt'
because it is being used by another process.
Text file is created, but I can't write to it.
When you create your StreamWriter object, you're specifying the same file that you already opened as a FileStream.
Use the constructor overload of StreamWriter that accepts your FileStream object, instead of specifying the file again, like this:
using (StreamWriter sw = new StreamWriter(fs))
I would simply do this:
public void AddNews(string path, string News_Title, string New_Desc)
{
string fileloc = Path.Combine(path, News_Title+".txt");
if (!File.Exists(fileloc)) {
File.WriteAllText(fileloc, New_Desc);
}
}
Note that I use Path.Combine as a better way to create paths, and File.WriteAllText as a simple way of creating a file and writing something to it. As MSDN says:
If the target file already exists, it is overwritten.
so we first check if the file already exists, as you did. If you want to overwrite its contents, just don't check and write directly.
The issue could be that the file is open or in use. Consider checking if the file is open before writing to it...
public bool IsFileOpen(FileInfo file)
{
FileStream stream = null;
try
{
stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException)
{
// Is Open
return true;
}
finally
{
if (stream != null)
stream.Close();
}
//Not Open
return false;
}
Good Luck!
using (TextWriter tw = new StreamWriter(path, true))
{
tw.WriteLine("The next line!");
}

How I can display Stream on the page?

I have a WCF method that I am calling, the method suppose to create a file but it create an exception. I try to find what is in the stream request that I am passing to this method. How I can alert or write this stream so I can find the content. That is my method:
Stream UploadImage(Stream request)
{
Stream requestTest = request;
HttpMultipartParser parser = new HttpMultipartParser(request, "data");
string filePath = "";
string passed = "";
if (parser.Success)
{
// Save the file somewhere
//File.WriteAllBytes(FILE_PATH + title + FILE_EXT, parser.FileContents);
// Save the file
//SaveFile( mtp.Filename, mtp.ContentType, mtp.FileContents);
FileStream fileStream = null;
BinaryWriter writer = null;
try
{
filePath = HttpContext.Current.Server.MapPath("Uploded\\test.jpg"); // BuildFilePath(strFileName, true);
filePath = filePath.Replace("SSGTrnService\\", "");
fileStream = new FileStream(filePath, FileMode.Create);
it produces an error on this line :
fileStream = new FileStream(filePath, FileMode.Create);
that I try to understand why file can not created.
Given the information you gave, I can only assume that your code tries to create the file test.jpg somewhere where your application is not allowed to write. A common mistake would be somewhere in the Program files folder. In modern Windows versions, that is specially protected.

C# - Appending text files

I have code that reads a file and then converts it to a string, the string is then written to a new file, although could someone demonstrate how to append this string to the destination file (rather than overwriting it)
private static void Ignore()
{
System.IO.StreamReader myFile =
new System.IO.StreamReader("c:\\test.txt");
string myString = myFile.ReadToEnd();
myFile.Close();
Console.WriteLine(myString);
// Write the string to a file.
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test2.txt");
file.WriteLine(myString);
file.Close();
}
If the file is small, you can read and write in two code lines.
var myString = File.ReadAllText("c:\\test.txt");
File.AppendAllText("c:\\test2.txt", myString);
If the file is huge, you can read and write line-by-line:
using (var source = new StreamReader("c:\\test.txt"))
using (var destination = File.AppendText("c:\\test2.txt"))
{
var line = source.ReadLine();
destination.WriteLine(line);
}
using(StreamWriter file = File.AppendText(#"c:\test2.txt"))
{
file.WriteLine(myString);
}
Use File.AppendAllText
File.AppendAllText("c:\\test2.txt", myString)
Also to read it, you can use File.ReadAllText to read it. Otherwise use a using statement to Dispose of the stream once you're done with the file.
Try
StreamWriter writer = File.AppendText("C:\\test.txt");
writer.WriteLine(mystring);

Categories

Resources