I created a simple console application to use StreamReader to read a CSV file, but it produces the following error:
Unhandled exception. System.ArgumentNullException: Value cannot be null. (Parameter 'stream')
at System.IO.StreamReader..ctor(Stream stream, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize, Boolean leaveOpen)
at System.IO.StreamReader..ctor(Stream stream, Encoding encoding)
at StreamCsv.SeedCsv.GetCsvData() in C:\...\StreamCsv\SeedCsv.cs:line 25
at StreamCsv.Program.Main(String[] args) in C:\...\StreamCsv\Program.cs:line 9
watch : Exited with error code -532462766
watch : Waiting for a file to change before restarting dotnet...
All of the following files are located in the same folder:
Program.cs - This is the main program:
using System;
namespace StreamCsv
{
class Program
{
static void Main(string[] args)
{
SeedCsv.GetCsvData();
}
}
}
SeedCsv.cs - This is the file that calls for StreamReader to process the csv file. The Build Action of the csv file has been set to Embedded Resource inside .csproj file.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using CsvHelper;
using StreamCsv.Domain;
namespace StreamCsv
{
public class SeedCsv
{
public static Geocoding[] GetCsvData()
{
Assembly assembly = Assembly.GetExecutingAssembly();
string resource = "open_postcode_geo_snippet.csv";
List<Geocoding> result = new List<Geocoding>();
using (Stream stream = assembly.GetManifestResourceStream(resource))
{
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
CsvReader csvReader = new CsvReader(reader, CultureInfo.CreateSpecificCulture("en"));
var data = csvReader.GetRecords<Geocoding>().ToArray();
return data;
}
}
}
}
}
StreamCsv.csproj - The csv file has been set to Embedded Resource inside .csproj file, in order to be processed by assembly.GetManifestResourceStream()
.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<EmbeddedResource Include="open_postcode_geo_snippet.csv" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="CsvHelper" Version="27.2.0" />
</ItemGroup>
</Project>
When I run this console, this line of code using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
is producing the error Unhandled exception. System.ArgumentNullException: Value cannot be null. (Parameter 'stream')
.
Can anyone point out what's wrong with my code?