SftpTests.cs 225 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340
  1. using System.Diagnostics;
  2. using Renci.SshNet.Common;
  3. using Renci.SshNet.IntegrationTests.Common;
  4. using Renci.SshNet.Sftp;
  5. namespace Renci.SshNet.IntegrationTests
  6. {
  7. // TODO: DeleteDirectory (fail + success
  8. // TODO: DeleteFile (fail + success
  9. // TODO: Delete (fail + success
  10. [TestClass]
  11. public class SftpTests : TestBase
  12. {
  13. private IConnectionInfoFactory _connectionInfoFactory;
  14. private IConnectionInfoFactory _adminConnectionInfoFactory;
  15. private IRemotePathTransformation _remotePathTransformation;
  16. [TestInitialize]
  17. public void SetUp()
  18. {
  19. _connectionInfoFactory = new LinuxVMConnectionFactory(SshServerHostName, SshServerPort);
  20. _adminConnectionInfoFactory = new LinuxAdminConnectionFactory(SshServerHostName, SshServerPort);
  21. _remotePathTransformation = RemotePathTransformation.ShellQuote;
  22. }
  23. [DataTestMethod]
  24. [DynamicData(nameof(GetSftpUploadFileFileStreamData), DynamicDataSourceType.Method)]
  25. public void Sftp_UploadFile_FileStream(int size)
  26. {
  27. var file = CreateTempFile(size);
  28. using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
  29. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  30. {
  31. client.Connect();
  32. var remoteFile = GenerateUniqueRemoteFileName();
  33. if (client.Exists(remoteFile))
  34. {
  35. client.Delete(remoteFile);
  36. }
  37. try
  38. {
  39. client.UploadFile(fs, remoteFile);
  40. using (var memoryStream = new MemoryStream(size))
  41. {
  42. client.DownloadFile(remoteFile, memoryStream);
  43. memoryStream.Position = 0;
  44. Assert.AreEqual(CreateFileHash(file), CreateHash(memoryStream));
  45. }
  46. }
  47. finally
  48. {
  49. if (client.Exists(remoteFile))
  50. {
  51. client.Delete(remoteFile);
  52. }
  53. }
  54. }
  55. }
  56. [TestMethod]
  57. public void Sftp_ConnectDisconnect_Serial()
  58. {
  59. const int iterations = 100;
  60. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  61. {
  62. for (var i = 1; i <= iterations; i++)
  63. {
  64. client.Connect();
  65. client.Disconnect();
  66. }
  67. }
  68. }
  69. [TestMethod]
  70. public void Sftp_ConnectDisconnect_Parallel()
  71. {
  72. const int iterations = 10;
  73. const int threads = 5;
  74. var startEvent = new ManualResetEvent(false);
  75. var tasks = Enumerable.Range(1, threads).Select(i =>
  76. {
  77. return Task.Factory.StartNew(() =>
  78. {
  79. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  80. {
  81. startEvent.WaitOne();
  82. for (var j = 0; j < iterations; j++)
  83. {
  84. client.Connect();
  85. client.Disconnect();
  86. }
  87. }
  88. });
  89. }).ToArray();
  90. startEvent.Set();
  91. Task.WaitAll(tasks);
  92. }
  93. [TestMethod]
  94. public void Sftp_BeginUploadFile()
  95. {
  96. const string content = "SftpBeginUploadFile";
  97. var expectedByteCount = (ulong)Encoding.ASCII.GetByteCount(content);
  98. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  99. {
  100. client.Connect();
  101. var remoteFile = GenerateUniqueRemoteFileName();
  102. if (client.Exists(remoteFile))
  103. {
  104. client.Delete(remoteFile);
  105. }
  106. try
  107. {
  108. using (var memoryStream = new MemoryStream(Encoding.ASCII.GetBytes(content)))
  109. {
  110. IAsyncResult asyncResultCallback = null;
  111. using var callbackCalled = new ManualResetEventSlim(false);
  112. var asyncResult = client.BeginUploadFile(memoryStream, remoteFile, ar =>
  113. {
  114. asyncResultCallback = ar;
  115. callbackCalled.Set();
  116. });
  117. Assert.IsTrue(asyncResult.AsyncWaitHandle.WaitOne(10000));
  118. // check async result
  119. var sftpUploadAsyncResult = asyncResult as SftpUploadAsyncResult;
  120. Assert.IsNotNull(sftpUploadAsyncResult);
  121. Assert.IsFalse(sftpUploadAsyncResult.IsUploadCanceled);
  122. Assert.IsTrue(sftpUploadAsyncResult.IsCompleted);
  123. Assert.IsFalse(sftpUploadAsyncResult.CompletedSynchronously);
  124. Assert.AreEqual(expectedByteCount, sftpUploadAsyncResult.UploadedBytes);
  125. Assert.IsTrue(callbackCalled.Wait(10000));
  126. // check async result callback
  127. var sftpUploadAsyncResultCallback = asyncResultCallback as SftpUploadAsyncResult;
  128. Assert.IsNotNull(sftpUploadAsyncResultCallback);
  129. Assert.IsFalse(sftpUploadAsyncResultCallback.IsUploadCanceled);
  130. Assert.IsTrue(sftpUploadAsyncResultCallback.IsCompleted);
  131. Assert.IsFalse(sftpUploadAsyncResultCallback.CompletedSynchronously);
  132. Assert.AreEqual(expectedByteCount, sftpUploadAsyncResultCallback.UploadedBytes);
  133. }
  134. // check uploaded file
  135. using (var memoryStream = new MemoryStream())
  136. {
  137. client.DownloadFile(remoteFile, memoryStream);
  138. memoryStream.Position = 0;
  139. var remoteContent = Encoding.ASCII.GetString(memoryStream.ToArray());
  140. Assert.AreEqual(content, remoteContent);
  141. }
  142. }
  143. finally
  144. {
  145. if (client.Exists(remoteFile))
  146. {
  147. client.Delete(remoteFile);
  148. }
  149. }
  150. }
  151. }
  152. [TestMethod]
  153. public void Sftp_Create_ExistingFile()
  154. {
  155. var encoding = Encoding.UTF8;
  156. var initialContent = "Gert & Ann & Lisa";
  157. var newContent1 = "Sofie";
  158. var newContent1Bytes = GetBytesWithPreamble(newContent1, encoding);
  159. var newContent2 = "Lisa & Sofie";
  160. var newContent2Bytes = GetBytesWithPreamble(newContent2, encoding);
  161. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  162. {
  163. client.Connect();
  164. var remoteFile = GenerateUniqueRemoteFileName();
  165. if (client.Exists(remoteFile))
  166. {
  167. client.DeleteFile(remoteFile);
  168. }
  169. try
  170. {
  171. client.WriteAllText(remoteFile, initialContent);
  172. #region Write less bytes than the current content, overwriting part of that content
  173. using (var fs = client.Create(remoteFile))
  174. using (var sw = new StreamWriter(fs, encoding))
  175. {
  176. sw.Write(newContent1);
  177. }
  178. var actualContent1 = client.ReadAllBytes(remoteFile);
  179. Assert.IsTrue(newContent1Bytes.IsEqualTo(actualContent1));
  180. #endregion Write less bytes than the current content, overwriting part of that content
  181. #region Write more bytes than the current content, overwriting and appending to that content
  182. using (var fs = client.Create(remoteFile))
  183. using (var sw = new StreamWriter(fs, encoding))
  184. {
  185. sw.Write(newContent2);
  186. }
  187. var actualContent2 = client.ReadAllBytes(remoteFile);
  188. Assert.IsTrue(newContent2Bytes.IsEqualTo(actualContent2));
  189. #endregion Write more bytes than the current content, overwriting and appending to that content
  190. }
  191. finally
  192. {
  193. if (client.Exists(remoteFile))
  194. {
  195. client.DeleteFile(remoteFile);
  196. }
  197. }
  198. }
  199. }
  200. [TestMethod]
  201. public void Sftp_Create_DirectoryDoesNotExist()
  202. {
  203. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  204. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  205. {
  206. client.Connect();
  207. if (client.Exists(remoteFile))
  208. {
  209. client.DeleteFile(remoteFile);
  210. }
  211. SftpFileStream fs = null;
  212. try
  213. {
  214. fs = client.Create(remoteFile);
  215. Assert.Fail();
  216. }
  217. catch (SftpPathNotFoundException ex)
  218. {
  219. Assert.IsNull(ex.InnerException);
  220. Assert.AreEqual("No such file", ex.Message);
  221. }
  222. finally
  223. {
  224. fs?.Dispose();
  225. if (client.Exists(remoteFile))
  226. {
  227. client.DeleteFile(remoteFile);
  228. }
  229. }
  230. }
  231. }
  232. [TestMethod]
  233. public void Sftp_Create_FileDoesNotExist()
  234. {
  235. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  236. {
  237. client.BufferSize = 512 * 1024;
  238. client.Connect();
  239. var remoteFile = GenerateUniqueRemoteFileName();
  240. if (client.Exists(remoteFile))
  241. {
  242. client.DeleteFile(remoteFile);
  243. }
  244. try
  245. {
  246. using (var imageStream = GetData("resources.issue #70.png"))
  247. {
  248. using (var fs = client.Create(remoteFile))
  249. {
  250. byte[] buffer = new byte[Math.Min(client.BufferSize, imageStream.Length)];
  251. int bytesRead;
  252. while ((bytesRead = imageStream.Read(buffer, offset: 0, buffer.Length)) > 0)
  253. {
  254. fs.Write(buffer, offset: 0, bytesRead);
  255. }
  256. }
  257. using (var memoryStream = new MemoryStream())
  258. {
  259. client.DownloadFile(remoteFile, memoryStream);
  260. memoryStream.Position = 0;
  261. imageStream.Position = 0;
  262. Assert.AreEqual(CreateHash(imageStream), CreateHash(memoryStream));
  263. }
  264. }
  265. }
  266. finally
  267. {
  268. if (client.Exists(remoteFile))
  269. {
  270. client.DeleteFile(remoteFile);
  271. }
  272. }
  273. }
  274. }
  275. [TestMethod]
  276. public void Sftp_AppendAllLines_NoEncoding_ExistingFile()
  277. {
  278. var initialContent = "\u0100ert & Ann";
  279. IEnumerable<string> linesToAppend = new[] { "Forever", "&", "\u0116ver" };
  280. var expectedContent = initialContent + string.Join(Environment.NewLine, linesToAppend) +
  281. Environment.NewLine;
  282. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  283. {
  284. client.Connect();
  285. var remoteFile = GenerateUniqueRemoteFileName();
  286. if (client.Exists(remoteFile))
  287. {
  288. client.DeleteFile(remoteFile);
  289. }
  290. try
  291. {
  292. client.WriteAllText(remoteFile, initialContent);
  293. client.AppendAllLines(remoteFile, linesToAppend);
  294. var text = client.ReadAllText(remoteFile);
  295. Assert.AreEqual(expectedContent, text);
  296. // ensure we didn't write an UTF-8 BOM
  297. using (var fs = client.OpenRead(remoteFile))
  298. {
  299. var firstByte = fs.ReadByte();
  300. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  301. }
  302. }
  303. finally
  304. {
  305. if (client.Exists(remoteFile))
  306. {
  307. client.DeleteFile(remoteFile);
  308. }
  309. }
  310. }
  311. }
  312. [TestMethod]
  313. public void Sftp_AppendAllLines_NoEncoding_DirectoryDoesNotExist()
  314. {
  315. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  316. IEnumerable<string> linesToAppend = new[] { "\u0139isa", "&", "Sofie" };
  317. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  318. {
  319. client.Connect();
  320. if (client.Exists(remoteFile))
  321. {
  322. client.DeleteFile(remoteFile);
  323. }
  324. try
  325. {
  326. client.AppendAllLines(remoteFile, linesToAppend);
  327. Assert.Fail();
  328. }
  329. catch (SftpPathNotFoundException ex)
  330. {
  331. Assert.IsNull(ex.InnerException);
  332. Assert.AreEqual("No such file", ex.Message);
  333. }
  334. finally
  335. {
  336. if (client.Exists(remoteFile))
  337. {
  338. client.DeleteFile(remoteFile);
  339. }
  340. }
  341. }
  342. }
  343. [TestMethod]
  344. public void Sftp_AppendAllLines_NoEncoding_FileDoesNotExist()
  345. {
  346. IEnumerable<string> linesToAppend = new[] { "\u0139isa", "&", "Sofie" };
  347. var expectedContent = string.Join(Environment.NewLine, linesToAppend) + Environment.NewLine;
  348. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  349. {
  350. client.Connect();
  351. var remoteFile = GenerateUniqueRemoteFileName();
  352. if (client.Exists(remoteFile))
  353. {
  354. client.DeleteFile(remoteFile);
  355. }
  356. try
  357. {
  358. client.AppendAllLines(remoteFile, linesToAppend);
  359. var text = client.ReadAllText(remoteFile);
  360. Assert.AreEqual(expectedContent, text);
  361. // ensure we didn't write an UTF-8 BOM
  362. using (var fs = client.OpenRead(remoteFile))
  363. {
  364. var firstByte = fs.ReadByte();
  365. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  366. }
  367. }
  368. finally
  369. {
  370. if (client.Exists(remoteFile))
  371. {
  372. client.DeleteFile(remoteFile);
  373. }
  374. }
  375. }
  376. }
  377. [TestMethod]
  378. public void Sftp_AppendAllText_NoEncoding_ExistingFile()
  379. {
  380. var initialContent = "\u0100ert & Ann";
  381. var contentToAppend = "Forever&\u0116ver";
  382. var expectedContent = initialContent + contentToAppend;
  383. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  384. {
  385. client.Connect();
  386. var remoteFile = GenerateUniqueRemoteFileName();
  387. if (client.Exists(remoteFile))
  388. {
  389. client.DeleteFile(remoteFile);
  390. }
  391. try
  392. {
  393. client.WriteAllText(remoteFile, initialContent);
  394. client.AppendAllText(remoteFile, contentToAppend);
  395. var text = client.ReadAllText(remoteFile);
  396. Assert.AreEqual(expectedContent, text);
  397. // ensure we didn't write an UTF-8 BOM
  398. using (var fs = client.OpenRead(remoteFile))
  399. {
  400. var firstByte = fs.ReadByte();
  401. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  402. }
  403. }
  404. finally
  405. {
  406. if (client.Exists(remoteFile))
  407. {
  408. client.DeleteFile(remoteFile);
  409. }
  410. }
  411. }
  412. }
  413. [TestMethod]
  414. public void Sftp_AppendAllText_NoEncoding_DirectoryDoesNotExist()
  415. {
  416. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  417. var contentToAppend = "Forever&\u0116ver";
  418. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  419. {
  420. client.Connect();
  421. if (client.Exists(remoteFile))
  422. {
  423. client.DeleteFile(remoteFile);
  424. }
  425. try
  426. {
  427. client.AppendAllText(remoteFile, contentToAppend);
  428. Assert.Fail();
  429. }
  430. catch (SftpPathNotFoundException ex)
  431. {
  432. Assert.IsNull(ex.InnerException);
  433. Assert.AreEqual("No such file", ex.Message);
  434. }
  435. finally
  436. {
  437. if (client.Exists(remoteFile))
  438. {
  439. client.DeleteFile(remoteFile);
  440. }
  441. }
  442. }
  443. }
  444. [TestMethod]
  445. public void Sftp_AppendAllText_NoEncoding_FileDoesNotExist()
  446. {
  447. var contentToAppend = "Forever&\u0116ver";
  448. var expectedContent = contentToAppend;
  449. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  450. {
  451. client.Connect();
  452. var remoteFile = GenerateUniqueRemoteFileName();
  453. if (client.Exists(remoteFile))
  454. {
  455. client.DeleteFile(remoteFile);
  456. }
  457. try
  458. {
  459. client.AppendAllText(remoteFile, contentToAppend);
  460. var text = client.ReadAllText(remoteFile);
  461. Assert.AreEqual(expectedContent, text);
  462. // ensure we didn't write an UTF-8 BOM
  463. using (var fs = client.OpenRead(remoteFile))
  464. {
  465. var firstByte = fs.ReadByte();
  466. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  467. }
  468. }
  469. finally
  470. {
  471. if (client.Exists(remoteFile))
  472. {
  473. client.DeleteFile(remoteFile);
  474. }
  475. }
  476. }
  477. }
  478. [TestMethod]
  479. public void Sftp_AppendText_NoEncoding_ExistingFile()
  480. {
  481. var initialContent = "\u0100ert & Ann";
  482. var contentToAppend = "Forever&\u0116ver";
  483. var expectedContent = initialContent + contentToAppend;
  484. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  485. {
  486. client.Connect();
  487. var remoteFile = GenerateUniqueRemoteFileName();
  488. if (client.Exists(remoteFile))
  489. {
  490. client.DeleteFile(remoteFile);
  491. }
  492. try
  493. {
  494. client.WriteAllText(remoteFile, initialContent);
  495. using (var sw = client.AppendText(remoteFile))
  496. {
  497. sw.Write(contentToAppend);
  498. }
  499. var text = client.ReadAllText(remoteFile);
  500. Assert.AreEqual(expectedContent, text);
  501. // ensure we didn't write an UTF-8 BOM
  502. using (var fs = client.OpenRead(remoteFile))
  503. {
  504. var firstByte = fs.ReadByte();
  505. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  506. }
  507. }
  508. finally
  509. {
  510. if (client.Exists(remoteFile))
  511. {
  512. client.DeleteFile(remoteFile);
  513. }
  514. }
  515. }
  516. }
  517. [TestMethod]
  518. public void Sftp_AppendText_NoEncoding_DirectoryDoesNotExist()
  519. {
  520. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  521. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  522. {
  523. client.Connect();
  524. if (client.Exists(remoteFile))
  525. {
  526. client.DeleteFile(remoteFile);
  527. }
  528. StreamWriter sw = null;
  529. try
  530. {
  531. sw = client.AppendText(remoteFile);
  532. Assert.Fail();
  533. }
  534. catch (SftpPathNotFoundException ex)
  535. {
  536. Assert.IsNull(ex.InnerException);
  537. Assert.AreEqual("No such file", ex.Message);
  538. }
  539. finally
  540. {
  541. sw?.Dispose();
  542. if (client.Exists(remoteFile))
  543. {
  544. client.DeleteFile(remoteFile);
  545. }
  546. }
  547. }
  548. }
  549. [TestMethod]
  550. public void Sftp_AppendText_NoEncoding_FileDoesNotExist()
  551. {
  552. var contentToAppend = "\u0100ert & Ann";
  553. var expectedContent = contentToAppend;
  554. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  555. {
  556. client.Connect();
  557. var remoteFile = GenerateUniqueRemoteFileName();
  558. if (client.Exists(remoteFile))
  559. {
  560. client.DeleteFile(remoteFile);
  561. }
  562. try
  563. {
  564. using (var sw = client.AppendText(remoteFile))
  565. {
  566. sw.Write(contentToAppend);
  567. }
  568. // ensure we didn't write an UTF-8 BOM
  569. using (var fs = client.OpenRead(remoteFile))
  570. {
  571. var firstByte = fs.ReadByte();
  572. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  573. }
  574. }
  575. finally
  576. {
  577. if (client.Exists(remoteFile))
  578. {
  579. client.DeleteFile(remoteFile);
  580. }
  581. }
  582. }
  583. }
  584. [TestMethod]
  585. public void Sftp_AppendAllLines_Encoding_ExistingFile()
  586. {
  587. var initialContent = "\u0100ert & Ann";
  588. IEnumerable<string> linesToAppend = new[] { "Forever", "&", "\u0116ver" };
  589. var expectedContent = initialContent + string.Join(Environment.NewLine, linesToAppend) +
  590. Environment.NewLine;
  591. var encoding = GetRandomEncoding();
  592. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  593. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  594. {
  595. client.Connect();
  596. var remoteFile = GenerateUniqueRemoteFileName();
  597. if (client.Exists(remoteFile))
  598. {
  599. client.DeleteFile(remoteFile);
  600. }
  601. try
  602. {
  603. client.WriteAllText(remoteFile, initialContent, encoding);
  604. client.AppendAllLines(remoteFile, linesToAppend, encoding);
  605. var text = client.ReadAllText(remoteFile, encoding);
  606. Assert.AreEqual(expectedContent, text);
  607. using (var fs = client.OpenRead(remoteFile))
  608. {
  609. var actualBytes = new byte[fs.Length];
  610. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  611. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  612. }
  613. }
  614. finally
  615. {
  616. if (client.Exists(remoteFile))
  617. {
  618. client.DeleteFile(remoteFile);
  619. }
  620. }
  621. }
  622. }
  623. [TestMethod]
  624. public void Sftp_AppendAllLines_Encoding_DirectoryDoesNotExist()
  625. {
  626. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  627. IEnumerable<string> linesToAppend = new[] { "Forever", "&", "\u0116ver" };
  628. var encoding = GetRandomEncoding();
  629. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  630. {
  631. client.Connect();
  632. if (client.Exists(remoteFile))
  633. {
  634. client.DeleteFile(remoteFile);
  635. }
  636. try
  637. {
  638. client.AppendAllLines(remoteFile, linesToAppend, encoding);
  639. Assert.Fail();
  640. }
  641. catch (SftpPathNotFoundException ex)
  642. {
  643. Assert.IsNull(ex.InnerException);
  644. Assert.AreEqual("No such file", ex.Message);
  645. }
  646. finally
  647. {
  648. if (client.Exists(remoteFile))
  649. {
  650. client.DeleteFile(remoteFile);
  651. }
  652. }
  653. }
  654. }
  655. [TestMethod]
  656. public void Sftp_AppendAllLines_Encoding_FileDoesNotExist()
  657. {
  658. IEnumerable<string> linesToAppend = new[] { "\u0139isa", "&", "Sofie" };
  659. var expectedContent = string.Join(Environment.NewLine, linesToAppend) + Environment.NewLine;
  660. var encoding = GetRandomEncoding();
  661. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  662. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  663. {
  664. client.Connect();
  665. var remoteFile = GenerateUniqueRemoteFileName();
  666. if (client.Exists(remoteFile))
  667. {
  668. client.DeleteFile(remoteFile);
  669. }
  670. try
  671. {
  672. client.AppendAllLines(remoteFile, linesToAppend, encoding);
  673. var text = client.ReadAllText(remoteFile, encoding);
  674. Assert.AreEqual(expectedContent, text);
  675. using (var fs = client.OpenRead(remoteFile))
  676. {
  677. var actualBytes = new byte[fs.Length];
  678. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  679. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  680. }
  681. }
  682. finally
  683. {
  684. if (client.Exists(remoteFile))
  685. {
  686. client.DeleteFile(remoteFile);
  687. }
  688. }
  689. }
  690. }
  691. [TestMethod]
  692. public void Sftp_AppendAllText_Encoding_ExistingFile()
  693. {
  694. var initialContent = "\u0100ert & Ann";
  695. var contentToAppend = "Forever&\u0116ver";
  696. var expectedContent = initialContent + contentToAppend;
  697. var encoding = GetRandomEncoding();
  698. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  699. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  700. {
  701. client.Connect();
  702. var remoteFile = GenerateUniqueRemoteFileName();
  703. if (client.Exists(remoteFile))
  704. {
  705. client.DeleteFile(remoteFile);
  706. }
  707. try
  708. {
  709. client.WriteAllText(remoteFile, initialContent, encoding);
  710. client.AppendAllText(remoteFile, contentToAppend, encoding);
  711. var text = client.ReadAllText(remoteFile, encoding);
  712. Assert.AreEqual(expectedContent, text);
  713. using (var fs = client.OpenRead(remoteFile))
  714. {
  715. var actualBytes = new byte[fs.Length];
  716. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  717. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  718. }
  719. }
  720. finally
  721. {
  722. if (client.Exists(remoteFile))
  723. {
  724. client.DeleteFile(remoteFile);
  725. }
  726. }
  727. }
  728. }
  729. [TestMethod]
  730. public void Sftp_AppendAllText_Encoding_DirectoryDoesNotExist()
  731. {
  732. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  733. const string contentToAppend = "Forever&\u0116ver";
  734. var encoding = GetRandomEncoding();
  735. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  736. {
  737. client.Connect();
  738. if (client.Exists(remoteFile))
  739. {
  740. client.DeleteFile(remoteFile);
  741. }
  742. try
  743. {
  744. client.AppendAllText(remoteFile, contentToAppend, encoding);
  745. Assert.Fail();
  746. }
  747. catch (SftpPathNotFoundException ex)
  748. {
  749. Assert.IsNull(ex.InnerException);
  750. Assert.AreEqual("No such file", ex.Message);
  751. }
  752. finally
  753. {
  754. if (client.Exists(remoteFile))
  755. {
  756. client.DeleteFile(remoteFile);
  757. }
  758. }
  759. }
  760. }
  761. [TestMethod]
  762. public void Sftp_AppendAllText_Encoding_FileDoesNotExist()
  763. {
  764. const string contentToAppend = "Forever&\u0116ver";
  765. var expectedContent = contentToAppend;
  766. var encoding = GetRandomEncoding();
  767. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  768. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  769. {
  770. client.Connect();
  771. var remoteFile = GenerateUniqueRemoteFileName();
  772. if (client.Exists(remoteFile))
  773. {
  774. client.DeleteFile(remoteFile);
  775. }
  776. try
  777. {
  778. client.AppendAllText(remoteFile, contentToAppend, encoding);
  779. var text = client.ReadAllText(remoteFile, encoding);
  780. Assert.AreEqual(expectedContent, text);
  781. using (var fs = client.OpenRead(remoteFile))
  782. {
  783. var actualBytes = new byte[fs.Length];
  784. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  785. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  786. }
  787. }
  788. finally
  789. {
  790. if (client.Exists(remoteFile))
  791. {
  792. client.DeleteFile(remoteFile);
  793. }
  794. }
  795. }
  796. }
  797. [TestMethod]
  798. public void Sftp_AppendText_Encoding_ExistingFile()
  799. {
  800. const string initialContent = "\u0100ert & Ann";
  801. const string contentToAppend = "Forever&\u0116ver";
  802. var expectedContent = initialContent + contentToAppend;
  803. var encoding = GetRandomEncoding();
  804. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  805. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  806. {
  807. client.Connect();
  808. var remoteFile = GenerateUniqueRemoteFileName();
  809. if (client.Exists(remoteFile))
  810. {
  811. client.DeleteFile(remoteFile);
  812. }
  813. try
  814. {
  815. client.WriteAllText(remoteFile, initialContent, encoding);
  816. using (var sw = client.AppendText(remoteFile, encoding))
  817. {
  818. sw.Write(contentToAppend);
  819. }
  820. var text = client.ReadAllText(remoteFile, encoding);
  821. Assert.AreEqual(expectedContent, text);
  822. using (var fs = client.OpenRead(remoteFile))
  823. {
  824. var actualBytes = new byte[fs.Length];
  825. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  826. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  827. }
  828. }
  829. finally
  830. {
  831. if (client.Exists(remoteFile))
  832. {
  833. client.DeleteFile(remoteFile);
  834. }
  835. }
  836. }
  837. }
  838. [TestMethod]
  839. public void Sftp_AppendText_Encoding_DirectoryDoesNotExist()
  840. {
  841. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  842. var encoding = GetRandomEncoding();
  843. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  844. {
  845. client.Connect();
  846. if (client.Exists(remoteFile))
  847. {
  848. client.DeleteFile(remoteFile);
  849. }
  850. StreamWriter sw = null;
  851. try
  852. {
  853. sw = client.AppendText(remoteFile, encoding);
  854. Assert.Fail();
  855. }
  856. catch (SftpPathNotFoundException ex)
  857. {
  858. Assert.IsNull(ex.InnerException);
  859. Assert.AreEqual("No such file", ex.Message);
  860. }
  861. finally
  862. {
  863. sw?.Dispose();
  864. if (client.Exists(remoteFile))
  865. {
  866. client.DeleteFile(remoteFile);
  867. }
  868. }
  869. }
  870. }
  871. [TestMethod]
  872. public void Sftp_AppendText_Encoding_FileDoesNotExist()
  873. {
  874. var encoding = GetRandomEncoding();
  875. const string contentToAppend = "\u0100ert & Ann";
  876. var expectedBytes = GetBytesWithPreamble(contentToAppend, encoding);
  877. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  878. {
  879. client.Connect();
  880. var remoteFile = GenerateUniqueRemoteFileName();
  881. if (client.Exists(remoteFile))
  882. {
  883. client.DeleteFile(remoteFile);
  884. }
  885. try
  886. {
  887. using (var sw = client.AppendText(remoteFile, encoding))
  888. {
  889. sw.Write(contentToAppend);
  890. }
  891. using (var fs = client.OpenRead(remoteFile))
  892. {
  893. var actualBytes = new byte[fs.Length];
  894. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  895. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  896. }
  897. }
  898. finally
  899. {
  900. if (client.Exists(remoteFile))
  901. {
  902. client.DeleteFile(remoteFile);
  903. }
  904. }
  905. }
  906. }
  907. [TestMethod]
  908. public void Sftp_CreateText_NoEncoding_ExistingFile()
  909. {
  910. var encoding = new UTF8Encoding(false, true);
  911. const string initialContent = "\u0100ert & Ann";
  912. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  913. const string newContent = "\u0116ver";
  914. const string expectedContent = "\u0116ver" + " & Ann";
  915. var expectedContentBytes = GetBytesWithPreamble(expectedContent, encoding);
  916. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  917. {
  918. client.Connect();
  919. var remoteFile = GenerateUniqueRemoteFileName();
  920. if (client.Exists(remoteFile))
  921. {
  922. client.DeleteFile(remoteFile);
  923. }
  924. try
  925. {
  926. client.WriteAllText(remoteFile, initialContent);
  927. using (client.CreateText(remoteFile))
  928. {
  929. }
  930. // verify that original content is left untouched
  931. using (var fs = client.OpenRead(remoteFile))
  932. {
  933. var actualBytes = new byte[fs.Length];
  934. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  935. Assert.IsTrue(initialContentBytes.IsEqualTo(actualBytes));
  936. }
  937. // write content that is less bytes than original content
  938. using (var sw = client.CreateText(remoteFile))
  939. {
  940. sw.Write(newContent);
  941. }
  942. // verify that original content is only partially overwritten
  943. var text = client.ReadAllText(remoteFile);
  944. Assert.AreEqual(expectedContent, text);
  945. using (var fs = client.OpenRead(remoteFile))
  946. {
  947. var actualBytes = new byte[fs.Length];
  948. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  949. Assert.IsTrue(expectedContentBytes.IsEqualTo(actualBytes));
  950. }
  951. }
  952. finally
  953. {
  954. if (client.Exists(remoteFile))
  955. {
  956. client.DeleteFile(remoteFile);
  957. }
  958. }
  959. }
  960. }
  961. [TestMethod]
  962. public void Sftp_CreateText_NoEncoding_DirectoryDoesNotExist()
  963. {
  964. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  965. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  966. {
  967. client.Connect();
  968. if (client.Exists(remoteFile))
  969. {
  970. client.DeleteFile(remoteFile);
  971. }
  972. StreamWriter sw = null;
  973. try
  974. {
  975. sw = client.CreateText(remoteFile);
  976. Assert.Fail();
  977. }
  978. catch (SftpPathNotFoundException ex)
  979. {
  980. Assert.IsNull(ex.InnerException);
  981. Assert.AreEqual("No such file", ex.Message);
  982. }
  983. finally
  984. {
  985. sw?.Dispose();
  986. if (client.Exists(remoteFile))
  987. {
  988. client.DeleteFile(remoteFile);
  989. }
  990. }
  991. }
  992. }
  993. [TestMethod]
  994. public void Sftp_CreateText_NoEncoding_FileDoesNotExist()
  995. {
  996. var encoding = new UTF8Encoding(false, true);
  997. var initialContent = "\u0100ert & Ann";
  998. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  999. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1000. {
  1001. client.Connect();
  1002. var remoteFile = GenerateUniqueRemoteFileName();
  1003. if (client.Exists(remoteFile))
  1004. {
  1005. client.DeleteFile(remoteFile);
  1006. }
  1007. try
  1008. {
  1009. using (client.CreateText(remoteFile))
  1010. {
  1011. }
  1012. // verify that empty file was created
  1013. Assert.IsTrue(client.Exists(remoteFile));
  1014. var file = client.GetAttributes(remoteFile);
  1015. Assert.AreEqual(0, file.Size);
  1016. client.DeleteFile(remoteFile);
  1017. using (var sw = client.CreateText(remoteFile))
  1018. {
  1019. sw.Write(initialContent);
  1020. }
  1021. // verify that content is written to file
  1022. var text = client.ReadAllText(remoteFile);
  1023. Assert.AreEqual(initialContent, text);
  1024. using (var fs = client.OpenRead(remoteFile))
  1025. {
  1026. var actualBytes = new byte[fs.Length];
  1027. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1028. Assert.IsTrue(initialContentBytes.IsEqualTo(actualBytes));
  1029. }
  1030. }
  1031. finally
  1032. {
  1033. if (client.Exists(remoteFile))
  1034. {
  1035. client.DeleteFile(remoteFile);
  1036. }
  1037. }
  1038. }
  1039. }
  1040. [TestMethod]
  1041. public void Sftp_CreateText_Encoding_ExistingFile()
  1042. {
  1043. var encoding = GetRandomEncoding();
  1044. var initialContent = "\u0100ert & Ann";
  1045. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  1046. var newContent = "\u0116ver";
  1047. var expectedContent = "\u0116ver" + " & Ann";
  1048. var expectedContentBytes = GetBytesWithPreamble(expectedContent, encoding);
  1049. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1050. {
  1051. client.Connect();
  1052. var remoteFile = GenerateUniqueRemoteFileName();
  1053. if (client.Exists(remoteFile))
  1054. {
  1055. client.DeleteFile(remoteFile);
  1056. }
  1057. try
  1058. {
  1059. client.WriteAllText(remoteFile, initialContent, encoding);
  1060. using (client.CreateText(remoteFile))
  1061. {
  1062. }
  1063. // verify that original content is left untouched
  1064. using (var fs = client.OpenRead(remoteFile))
  1065. {
  1066. var actualBytes = new byte[fs.Length];
  1067. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1068. Assert.IsTrue(initialContentBytes.IsEqualTo(actualBytes));
  1069. }
  1070. // write content that is less bytes than original content
  1071. using (var sw = client.CreateText(remoteFile, encoding))
  1072. {
  1073. sw.Write(newContent);
  1074. }
  1075. // verify that original content is only partially overwritten
  1076. var text = client.ReadAllText(remoteFile, encoding);
  1077. Assert.AreEqual(expectedContent, text);
  1078. using (var fs = client.OpenRead(remoteFile))
  1079. {
  1080. var actualBytes = new byte[fs.Length];
  1081. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1082. Assert.IsTrue(expectedContentBytes.IsEqualTo(actualBytes));
  1083. }
  1084. }
  1085. finally
  1086. {
  1087. if (client.Exists(remoteFile))
  1088. {
  1089. client.DeleteFile(remoteFile);
  1090. }
  1091. }
  1092. }
  1093. }
  1094. [TestMethod]
  1095. public void Sftp_CreateText_Encoding_DirectoryDoesNotExist()
  1096. {
  1097. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1098. var encoding = GetRandomEncoding();
  1099. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1100. {
  1101. client.Connect();
  1102. if (client.Exists(remoteFile))
  1103. {
  1104. client.DeleteFile(remoteFile);
  1105. }
  1106. StreamWriter sw = null;
  1107. try
  1108. {
  1109. sw = client.CreateText(remoteFile, encoding);
  1110. Assert.Fail();
  1111. }
  1112. catch (SftpPathNotFoundException ex)
  1113. {
  1114. Assert.IsNull(ex.InnerException);
  1115. Assert.AreEqual("No such file", ex.Message);
  1116. }
  1117. finally
  1118. {
  1119. sw?.Dispose();
  1120. if (client.Exists(remoteFile))
  1121. {
  1122. client.DeleteFile(remoteFile);
  1123. }
  1124. }
  1125. }
  1126. }
  1127. [TestMethod]
  1128. public void Sftp_CreateText_Encoding_FileDoesNotExist()
  1129. {
  1130. var encoding = GetRandomEncoding();
  1131. var initialContent = "\u0100ert & Ann";
  1132. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  1133. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1134. {
  1135. client.Connect();
  1136. var remoteFile = GenerateUniqueRemoteFileName();
  1137. if (client.Exists(remoteFile))
  1138. {
  1139. client.DeleteFile(remoteFile);
  1140. }
  1141. try
  1142. {
  1143. using (client.CreateText(remoteFile, encoding))
  1144. {
  1145. }
  1146. // verify that file containing only preamble was created
  1147. Assert.IsTrue(client.Exists(remoteFile));
  1148. var file = client.GetAttributes(remoteFile);
  1149. Assert.AreEqual(encoding.GetPreamble().Length, file.Size);
  1150. client.DeleteFile(remoteFile);
  1151. using (var sw = client.CreateText(remoteFile, encoding))
  1152. {
  1153. sw.Write(initialContent);
  1154. }
  1155. // verify that content is written to file
  1156. var text = client.ReadAllText(remoteFile, encoding);
  1157. Assert.AreEqual(initialContent, text);
  1158. using (var fs = client.OpenRead(remoteFile))
  1159. {
  1160. var actualBytes = new byte[fs.Length];
  1161. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1162. Assert.IsTrue(initialContentBytes.IsEqualTo(actualBytes));
  1163. }
  1164. }
  1165. finally
  1166. {
  1167. if (client.Exists(remoteFile))
  1168. {
  1169. client.DeleteFile(remoteFile);
  1170. }
  1171. }
  1172. }
  1173. }
  1174. [TestMethod]
  1175. public void Sftp_DownloadFile_FileDoesNotExist()
  1176. {
  1177. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1178. {
  1179. client.Connect();
  1180. var remoteFile = GenerateUniqueRemoteFileName();
  1181. if (client.Exists(remoteFile))
  1182. {
  1183. client.DeleteFile(remoteFile);
  1184. }
  1185. using (var ms = new MemoryStream())
  1186. {
  1187. try
  1188. {
  1189. client.DownloadFile(remoteFile, ms);
  1190. Assert.Fail();
  1191. }
  1192. catch (SftpPathNotFoundException ex)
  1193. {
  1194. Assert.IsNull(ex.InnerException);
  1195. Assert.AreEqual("No such file", ex.Message);
  1196. // ensure file was not created by us
  1197. Assert.IsFalse(client.Exists(remoteFile));
  1198. }
  1199. finally
  1200. {
  1201. if (client.Exists(remoteFile))
  1202. {
  1203. client.DeleteFile(remoteFile);
  1204. }
  1205. }
  1206. }
  1207. }
  1208. }
  1209. [TestMethod]
  1210. public void Sftp_ReadAllBytes_ExistingFile()
  1211. {
  1212. var encoding = GetRandomEncoding();
  1213. var content = "\u0100ert & Ann";
  1214. var contentBytes = GetBytesWithPreamble(content, encoding);
  1215. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1216. {
  1217. client.Connect();
  1218. var remoteFile = GenerateUniqueRemoteFileName();
  1219. if (client.Exists(remoteFile))
  1220. {
  1221. client.DeleteFile(remoteFile);
  1222. }
  1223. try
  1224. {
  1225. client.WriteAllText(remoteFile, content, encoding);
  1226. var actualBytes = client.ReadAllBytes(remoteFile);
  1227. Assert.IsTrue(contentBytes.IsEqualTo(actualBytes));
  1228. }
  1229. finally
  1230. {
  1231. if (client.Exists(remoteFile))
  1232. {
  1233. client.DeleteFile(remoteFile);
  1234. }
  1235. }
  1236. }
  1237. }
  1238. [TestMethod]
  1239. public void Sftp_ReadAllBytes_FileDoesNotExist()
  1240. {
  1241. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1242. {
  1243. client.Connect();
  1244. var remoteFile = GenerateUniqueRemoteFileName();
  1245. if (client.Exists(remoteFile))
  1246. {
  1247. client.DeleteFile(remoteFile);
  1248. }
  1249. try
  1250. {
  1251. client.ReadAllBytes(remoteFile);
  1252. Assert.Fail();
  1253. }
  1254. catch (SftpPathNotFoundException ex)
  1255. {
  1256. Assert.IsNull(ex.InnerException);
  1257. Assert.AreEqual("No such file", ex.Message);
  1258. // ensure file was not created by us
  1259. Assert.IsFalse(client.Exists(remoteFile));
  1260. }
  1261. finally
  1262. {
  1263. if (client.Exists(remoteFile))
  1264. {
  1265. client.DeleteFile(remoteFile);
  1266. }
  1267. }
  1268. }
  1269. }
  1270. [TestMethod]
  1271. public void Sftp_ReadAllLines_NoEncoding_ExistingFile()
  1272. {
  1273. var encoding = new UTF8Encoding(false, true);
  1274. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1275. var linesBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, lines) + Environment.NewLine,
  1276. encoding);
  1277. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1278. {
  1279. client.Connect();
  1280. var remoteFile = GenerateUniqueRemoteFileName();
  1281. if (client.Exists(remoteFile))
  1282. {
  1283. client.DeleteFile(remoteFile);
  1284. }
  1285. try
  1286. {
  1287. using (var sw = client.AppendText(remoteFile))
  1288. {
  1289. for (var i = 0; i < lines.Length; i++)
  1290. {
  1291. sw.WriteLine(lines[i]);
  1292. }
  1293. }
  1294. var actualLines = client.ReadAllLines(remoteFile);
  1295. Assert.IsNotNull(actualLines);
  1296. Assert.AreEqual(lines.Length, actualLines.Length);
  1297. for (var i = 0; i < lines.Length; i++)
  1298. {
  1299. Assert.AreEqual(lines[i], actualLines[i]);
  1300. }
  1301. using (var fs = client.OpenRead(remoteFile))
  1302. {
  1303. var actualBytes = new byte[fs.Length];
  1304. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1305. Assert.IsTrue(linesBytes.IsEqualTo(actualBytes));
  1306. }
  1307. }
  1308. finally
  1309. {
  1310. if (client.Exists(remoteFile))
  1311. {
  1312. client.DeleteFile(remoteFile);
  1313. }
  1314. }
  1315. }
  1316. }
  1317. [TestMethod]
  1318. public void Sftp_ReadAllLines_NoEncoding_FileDoesNotExist()
  1319. {
  1320. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1321. {
  1322. client.Connect();
  1323. var remoteFile = GenerateUniqueRemoteFileName();
  1324. if (client.Exists(remoteFile))
  1325. {
  1326. client.DeleteFile(remoteFile);
  1327. }
  1328. try
  1329. {
  1330. client.ReadAllLines(remoteFile);
  1331. Assert.Fail();
  1332. }
  1333. catch (SftpPathNotFoundException ex)
  1334. {
  1335. Assert.IsNull(ex.InnerException);
  1336. Assert.AreEqual("No such file", ex.Message);
  1337. // ensure file was not created by us
  1338. Assert.IsFalse(client.Exists(remoteFile));
  1339. }
  1340. finally
  1341. {
  1342. if (client.Exists(remoteFile))
  1343. {
  1344. client.DeleteFile(remoteFile);
  1345. }
  1346. }
  1347. }
  1348. }
  1349. [TestMethod]
  1350. public void Sftp_ReadAllLines_Encoding_ExistingFile()
  1351. {
  1352. var encoding = GetRandomEncoding();
  1353. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1354. var linesBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, lines) + Environment.NewLine,
  1355. encoding);
  1356. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1357. {
  1358. client.Connect();
  1359. var remoteFile = GenerateUniqueRemoteFileName();
  1360. if (client.Exists(remoteFile))
  1361. {
  1362. client.DeleteFile(remoteFile);
  1363. }
  1364. try
  1365. {
  1366. using (var sw = client.AppendText(remoteFile, encoding))
  1367. {
  1368. for (var i = 0; i < lines.Length; i++)
  1369. {
  1370. sw.WriteLine(lines[i]);
  1371. }
  1372. }
  1373. var actualLines = client.ReadAllLines(remoteFile, encoding);
  1374. Assert.IsNotNull(actualLines);
  1375. Assert.AreEqual(lines.Length, actualLines.Length);
  1376. for (var i = 0; i < lines.Length; i++)
  1377. {
  1378. Assert.AreEqual(lines[i], actualLines[i]);
  1379. }
  1380. using (var fs = client.OpenRead(remoteFile))
  1381. {
  1382. var actualBytes = new byte[fs.Length];
  1383. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1384. Assert.IsTrue(linesBytes.IsEqualTo(actualBytes));
  1385. }
  1386. }
  1387. finally
  1388. {
  1389. if (client.Exists(remoteFile))
  1390. {
  1391. client.DeleteFile(remoteFile);
  1392. }
  1393. }
  1394. }
  1395. }
  1396. [TestMethod]
  1397. public void Sftp_ReadAllLines_Encoding_FileDoesNotExist()
  1398. {
  1399. var encoding = GetRandomEncoding();
  1400. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1401. {
  1402. client.Connect();
  1403. var remoteFile = GenerateUniqueRemoteFileName();
  1404. if (client.Exists(remoteFile))
  1405. {
  1406. client.DeleteFile(remoteFile);
  1407. }
  1408. try
  1409. {
  1410. client.ReadAllLines(remoteFile, encoding);
  1411. Assert.Fail();
  1412. }
  1413. catch (SftpPathNotFoundException ex)
  1414. {
  1415. Assert.IsNull(ex.InnerException);
  1416. Assert.AreEqual("No such file", ex.Message);
  1417. // ensure file was not created by us
  1418. Assert.IsFalse(client.Exists(remoteFile));
  1419. }
  1420. finally
  1421. {
  1422. if (client.Exists(remoteFile))
  1423. {
  1424. client.DeleteFile(remoteFile);
  1425. }
  1426. }
  1427. }
  1428. }
  1429. [TestMethod]
  1430. public void Sftp_ReadAllText_NoEncoding_ExistingFile()
  1431. {
  1432. var encoding = new UTF8Encoding(false, true);
  1433. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1434. var expectedText = string.Join(Environment.NewLine, lines) + Environment.NewLine;
  1435. var expectedBytes = GetBytesWithPreamble(expectedText, encoding);
  1436. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1437. {
  1438. client.Connect();
  1439. var remoteFile = GenerateUniqueRemoteFileName();
  1440. if (client.Exists(remoteFile))
  1441. {
  1442. client.DeleteFile(remoteFile);
  1443. }
  1444. try
  1445. {
  1446. using (var sw = client.AppendText(remoteFile))
  1447. {
  1448. for (var i = 0; i < lines.Length; i++)
  1449. {
  1450. sw.WriteLine(lines[i]);
  1451. }
  1452. }
  1453. var actualText = client.ReadAllText(remoteFile);
  1454. Assert.AreEqual(actualText, expectedText);
  1455. using (var fs = client.OpenRead(remoteFile))
  1456. {
  1457. var actualBytes = new byte[fs.Length];
  1458. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1459. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  1460. }
  1461. }
  1462. finally
  1463. {
  1464. if (client.Exists(remoteFile))
  1465. {
  1466. client.DeleteFile(remoteFile);
  1467. }
  1468. }
  1469. }
  1470. }
  1471. [TestMethod]
  1472. public void Sftp_ReadAllText_NoEncoding_FileDoesNotExist()
  1473. {
  1474. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1475. {
  1476. client.Connect();
  1477. var remoteFile = GenerateUniqueRemoteFileName();
  1478. if (client.Exists(remoteFile))
  1479. {
  1480. client.DeleteFile(remoteFile);
  1481. }
  1482. try
  1483. {
  1484. client.ReadAllText(remoteFile);
  1485. Assert.Fail();
  1486. }
  1487. catch (SftpPathNotFoundException ex)
  1488. {
  1489. Assert.IsNull(ex.InnerException);
  1490. Assert.AreEqual("No such file", ex.Message);
  1491. // ensure file was not created by us
  1492. Assert.IsFalse(client.Exists(remoteFile));
  1493. }
  1494. finally
  1495. {
  1496. if (client.Exists(remoteFile))
  1497. {
  1498. client.DeleteFile(remoteFile);
  1499. }
  1500. }
  1501. }
  1502. }
  1503. [TestMethod]
  1504. public void Sftp_ReadAllText_Encoding_ExistingFile()
  1505. {
  1506. var encoding = GetRandomEncoding();
  1507. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1508. var expectedText = string.Join(Environment.NewLine, lines) + Environment.NewLine;
  1509. var expectedBytes = GetBytesWithPreamble(expectedText, encoding);
  1510. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1511. {
  1512. client.Connect();
  1513. var remoteFile = GenerateUniqueRemoteFileName();
  1514. if (client.Exists(remoteFile))
  1515. {
  1516. client.DeleteFile(remoteFile);
  1517. }
  1518. try
  1519. {
  1520. using (var sw = client.AppendText(remoteFile, encoding))
  1521. {
  1522. for (var i = 0; i < lines.Length; i++)
  1523. {
  1524. sw.WriteLine(lines[i]);
  1525. }
  1526. }
  1527. var actualText = client.ReadAllText(remoteFile, encoding);
  1528. Assert.AreEqual(expectedText, actualText);
  1529. using (var fs = client.OpenRead(remoteFile))
  1530. {
  1531. var actualBytes = new byte[fs.Length];
  1532. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1533. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  1534. }
  1535. }
  1536. finally
  1537. {
  1538. if (client.Exists(remoteFile))
  1539. {
  1540. client.DeleteFile(remoteFile);
  1541. }
  1542. }
  1543. }
  1544. }
  1545. [TestMethod]
  1546. public void Sftp_ReadAllText_Encoding_FileDoesNotExist()
  1547. {
  1548. var encoding = GetRandomEncoding();
  1549. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1550. {
  1551. client.Connect();
  1552. var remoteFile = GenerateUniqueRemoteFileName();
  1553. if (client.Exists(remoteFile))
  1554. {
  1555. client.DeleteFile(remoteFile);
  1556. }
  1557. try
  1558. {
  1559. client.ReadAllText(remoteFile, encoding);
  1560. Assert.Fail();
  1561. }
  1562. catch (SftpPathNotFoundException ex)
  1563. {
  1564. Assert.IsNull(ex.InnerException);
  1565. Assert.AreEqual("No such file", ex.Message);
  1566. // ensure file was not created by us
  1567. Assert.IsFalse(client.Exists(remoteFile));
  1568. }
  1569. finally
  1570. {
  1571. if (client.Exists(remoteFile))
  1572. {
  1573. client.DeleteFile(remoteFile);
  1574. }
  1575. }
  1576. }
  1577. }
  1578. [TestMethod]
  1579. public void Sftp_ReadLines_NoEncoding_ExistingFile()
  1580. {
  1581. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1582. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1583. {
  1584. client.Connect();
  1585. var remoteFile = GenerateUniqueRemoteFileName();
  1586. if (client.Exists(remoteFile))
  1587. {
  1588. client.DeleteFile(remoteFile);
  1589. }
  1590. try
  1591. {
  1592. using (var sw = client.AppendText(remoteFile))
  1593. {
  1594. for (var i = 0; i < lines.Length; i++)
  1595. {
  1596. sw.WriteLine(lines[i]);
  1597. }
  1598. }
  1599. var actualLines = client.ReadLines(remoteFile);
  1600. Assert.IsNotNull(actualLines);
  1601. var actualLinesEnum = actualLines.GetEnumerator();
  1602. for (var i = 0; i < lines.Length; i++)
  1603. {
  1604. Assert.IsTrue(actualLinesEnum.MoveNext());
  1605. var actualLine = actualLinesEnum.Current;
  1606. Assert.AreEqual(lines[i], actualLine);
  1607. }
  1608. Assert.IsFalse(actualLinesEnum.MoveNext());
  1609. }
  1610. finally
  1611. {
  1612. if (client.Exists(remoteFile))
  1613. {
  1614. client.DeleteFile(remoteFile);
  1615. }
  1616. }
  1617. }
  1618. }
  1619. [TestMethod]
  1620. public void Sftp_ReadLines_NoEncoding_FileDoesNotExist()
  1621. {
  1622. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1623. {
  1624. client.Connect();
  1625. var remoteFile = GenerateUniqueRemoteFileName();
  1626. if (client.Exists(remoteFile))
  1627. {
  1628. client.DeleteFile(remoteFile);
  1629. }
  1630. try
  1631. {
  1632. client.ReadLines(remoteFile);
  1633. Assert.Fail();
  1634. }
  1635. catch (SftpPathNotFoundException ex)
  1636. {
  1637. Assert.IsNull(ex.InnerException);
  1638. Assert.AreEqual("No such file", ex.Message);
  1639. // ensure file was not created by us
  1640. Assert.IsFalse(client.Exists(remoteFile));
  1641. }
  1642. finally
  1643. {
  1644. if (client.Exists(remoteFile))
  1645. {
  1646. client.DeleteFile(remoteFile);
  1647. }
  1648. }
  1649. }
  1650. }
  1651. [TestMethod]
  1652. public void Sftp_ReadLines_Encoding_ExistingFile()
  1653. {
  1654. var encoding = GetRandomEncoding();
  1655. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1656. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1657. {
  1658. client.Connect();
  1659. var remoteFile = GenerateUniqueRemoteFileName();
  1660. if (client.Exists(remoteFile))
  1661. {
  1662. client.DeleteFile(remoteFile);
  1663. }
  1664. try
  1665. {
  1666. using (var sw = client.AppendText(remoteFile, encoding))
  1667. {
  1668. for (var i = 0; i < lines.Length; i++)
  1669. {
  1670. sw.WriteLine(lines[i]);
  1671. }
  1672. }
  1673. var actualLines = client.ReadLines(remoteFile, encoding);
  1674. Assert.IsNotNull(actualLines);
  1675. using (var actualLinesEnum = actualLines.GetEnumerator())
  1676. {
  1677. for (var i = 0; i < lines.Length; i++)
  1678. {
  1679. Assert.IsTrue(actualLinesEnum.MoveNext());
  1680. var actualLine = actualLinesEnum.Current;
  1681. Assert.AreEqual(lines[i], actualLine);
  1682. }
  1683. Assert.IsFalse(actualLinesEnum.MoveNext());
  1684. }
  1685. }
  1686. finally
  1687. {
  1688. if (client.Exists(remoteFile))
  1689. {
  1690. client.DeleteFile(remoteFile);
  1691. }
  1692. }
  1693. }
  1694. }
  1695. [TestMethod]
  1696. public void Sftp_ReadLines_Encoding_FileDoesNotExist()
  1697. {
  1698. var encoding = GetRandomEncoding();
  1699. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1700. {
  1701. client.Connect();
  1702. var remoteFile = GenerateUniqueRemoteFileName();
  1703. if (client.Exists(remoteFile))
  1704. {
  1705. client.DeleteFile(remoteFile);
  1706. }
  1707. try
  1708. {
  1709. client.ReadLines(remoteFile, encoding);
  1710. Assert.Fail();
  1711. }
  1712. catch (SftpPathNotFoundException ex)
  1713. {
  1714. Assert.IsNull(ex.InnerException);
  1715. Assert.AreEqual("No such file", ex.Message);
  1716. // ensure file was not created by us
  1717. Assert.IsFalse(client.Exists(remoteFile));
  1718. }
  1719. finally
  1720. {
  1721. if (client.Exists(remoteFile))
  1722. {
  1723. client.DeleteFile(remoteFile);
  1724. }
  1725. }
  1726. }
  1727. }
  1728. [TestMethod]
  1729. public void Sftp_WriteAllBytes_DirectoryDoesNotExist()
  1730. {
  1731. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1732. var content = GenerateRandom(size: 5);
  1733. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1734. {
  1735. client.Connect();
  1736. if (client.Exists(remoteFile))
  1737. {
  1738. client.DeleteFile(remoteFile);
  1739. }
  1740. try
  1741. {
  1742. client.WriteAllBytes(remoteFile, content);
  1743. Assert.Fail();
  1744. }
  1745. catch (SftpPathNotFoundException ex)
  1746. {
  1747. Assert.IsNull(ex.InnerException);
  1748. Assert.AreEqual("No such file", ex.Message);
  1749. }
  1750. finally
  1751. {
  1752. if (client.Exists(remoteFile))
  1753. {
  1754. client.DeleteFile(remoteFile);
  1755. }
  1756. }
  1757. }
  1758. }
  1759. [TestMethod]
  1760. public void Sftp_WriteAllBytes_ExistingFile()
  1761. {
  1762. var initialContent = GenerateRandom(size: 13);
  1763. var newContent1 = GenerateRandom(size: 5);
  1764. var expectedContent1 = new ArrayBuilder<byte>().Add(newContent1)
  1765. .Add(initialContent, newContent1.Length, initialContent.Length - newContent1.Length)
  1766. .Build();
  1767. var newContent2 = GenerateRandom(size: 50000);
  1768. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1769. {
  1770. client.Connect();
  1771. var remoteFile = GenerateUniqueRemoteFileName();
  1772. if (client.Exists(remoteFile))
  1773. {
  1774. client.DeleteFile(remoteFile);
  1775. }
  1776. try
  1777. {
  1778. using (var fs = client.Create(remoteFile))
  1779. {
  1780. fs.Write(initialContent, offset: 0, initialContent.Length);
  1781. }
  1782. #region Write less bytes than the current content, overwriting part of that content
  1783. client.WriteAllBytes(remoteFile, newContent1);
  1784. var actualContent1 = client.ReadAllBytes(remoteFile);
  1785. Assert.IsTrue(expectedContent1.IsEqualTo(actualContent1));
  1786. #endregion Write less bytes than the initial content, overwriting part of that content
  1787. #region Write more bytes than the current content, overwriting and appending to that content
  1788. client.WriteAllBytes(remoteFile, newContent2);
  1789. var actualContent2 = client.ReadAllBytes(remoteFile);
  1790. Assert.IsTrue(newContent2.IsEqualTo(actualContent2));
  1791. #endregion Write less bytes than the initial content, overwriting part of that content
  1792. }
  1793. finally
  1794. {
  1795. if (client.Exists(remoteFile))
  1796. {
  1797. client.DeleteFile(remoteFile);
  1798. }
  1799. }
  1800. }
  1801. }
  1802. [TestMethod]
  1803. public void Sftp_WriteAllBytes_FileDoesNotExist()
  1804. {
  1805. var content = GenerateRandom(size: 13);
  1806. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1807. {
  1808. client.Connect();
  1809. var remoteFile = GenerateUniqueRemoteFileName();
  1810. if (client.Exists(remoteFile))
  1811. {
  1812. client.DeleteFile(remoteFile);
  1813. }
  1814. try
  1815. {
  1816. client.WriteAllBytes(remoteFile, content);
  1817. using (var fs = client.OpenRead(remoteFile))
  1818. {
  1819. var actualBytes = new byte[fs.Length];
  1820. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1821. Assert.IsTrue(content.IsEqualTo(actualBytes));
  1822. }
  1823. }
  1824. finally
  1825. {
  1826. if (client.Exists(remoteFile))
  1827. {
  1828. client.DeleteFile(remoteFile);
  1829. }
  1830. }
  1831. }
  1832. }
  1833. [TestMethod]
  1834. public void Sftp_WriteAllLines_IEnumerable_NoEncoding_DirectoryDoesNotExist()
  1835. {
  1836. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1837. IEnumerable<string> linesToWrite = new[] { "Forever", "&", "\u0116ver" };
  1838. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1839. {
  1840. client.Connect();
  1841. if (client.Exists(remoteFile))
  1842. {
  1843. client.DeleteFile(remoteFile);
  1844. }
  1845. try
  1846. {
  1847. client.WriteAllLines(remoteFile, linesToWrite);
  1848. Assert.Fail();
  1849. }
  1850. catch (SftpPathNotFoundException ex)
  1851. {
  1852. Assert.IsNull(ex.InnerException);
  1853. Assert.AreEqual("No such file", ex.Message);
  1854. }
  1855. finally
  1856. {
  1857. if (client.Exists(remoteFile))
  1858. {
  1859. client.DeleteFile(remoteFile);
  1860. }
  1861. }
  1862. }
  1863. }
  1864. [TestMethod]
  1865. public void Sftp_WriteAllLines_IEnumerable_NoEncoding_ExistingFile()
  1866. {
  1867. var encoding = new UTF8Encoding(false, true);
  1868. var initialContent = "\u0100ert & Ann Forever & Ever Lisa & Sofie";
  1869. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  1870. IEnumerable<string> linesToWrite1 = new[] { "Forever", "&", "\u0116ver" };
  1871. var linesToWrite1Bytes =
  1872. GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite1) + Environment.NewLine, encoding);
  1873. var expectedBytes1 = new ArrayBuilder<byte>().Add(linesToWrite1Bytes)
  1874. .Add(initialContentBytes,
  1875. linesToWrite1Bytes.Length,
  1876. initialContentBytes.Length - linesToWrite1Bytes.Length)
  1877. .Build();
  1878. IEnumerable<string> linesToWrite2 = new[] { "Forever", "&", "\u0116ver", "Gert & Ann", "Lisa + Sofie" };
  1879. var linesToWrite2Bytes =
  1880. GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite2) + Environment.NewLine, encoding);
  1881. var expectedBytes2 = linesToWrite2Bytes;
  1882. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1883. {
  1884. client.Connect();
  1885. var remoteFile = GenerateUniqueRemoteFileName();
  1886. if (client.Exists(remoteFile))
  1887. {
  1888. client.DeleteFile(remoteFile);
  1889. }
  1890. try
  1891. {
  1892. // create initial content
  1893. client.WriteAllText(remoteFile, initialContent);
  1894. #region Write less bytes than the current content, overwriting part of that content
  1895. client.WriteAllLines(remoteFile, linesToWrite1);
  1896. using (var fs = client.OpenRead(remoteFile))
  1897. {
  1898. var actualBytes = new byte[fs.Length];
  1899. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1900. Assert.IsTrue(expectedBytes1.IsEqualTo(actualBytes));
  1901. }
  1902. #endregion Write less bytes than the current content, overwriting part of that content
  1903. #region Write more bytes than the current content, overwriting and appending to that content
  1904. client.WriteAllLines(remoteFile, linesToWrite2);
  1905. using (var fs = client.OpenRead(remoteFile))
  1906. {
  1907. var actualBytes = new byte[fs.Length];
  1908. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1909. Assert.IsTrue(expectedBytes2.IsEqualTo(actualBytes));
  1910. }
  1911. #endregion Write more bytes than the current content, overwriting and appending to that content
  1912. }
  1913. finally
  1914. {
  1915. if (client.Exists(remoteFile))
  1916. {
  1917. client.DeleteFile(remoteFile);
  1918. }
  1919. }
  1920. }
  1921. }
  1922. [TestMethod]
  1923. public void Sftp_WriteAllLines_IEnumerable_NoEncoding_FileDoesNotExist()
  1924. {
  1925. var encoding = new UTF8Encoding(false, true);
  1926. IEnumerable<string> linesToWrite = new[] { "\u0139isa", "&", "Sofie" };
  1927. var linesToWriteBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite) + Environment.NewLine, encoding);
  1928. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1929. {
  1930. client.Connect();
  1931. var remoteFile = GenerateUniqueRemoteFileName();
  1932. if (client.Exists(remoteFile))
  1933. {
  1934. client.DeleteFile(remoteFile);
  1935. }
  1936. try
  1937. {
  1938. client.WriteAllLines(remoteFile, linesToWrite);
  1939. using (var fs = client.OpenRead(remoteFile))
  1940. {
  1941. var actualBytes = new byte[fs.Length];
  1942. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1943. Assert.IsTrue(linesToWriteBytes.IsEqualTo(actualBytes));
  1944. }
  1945. }
  1946. finally
  1947. {
  1948. if (client.Exists(remoteFile))
  1949. {
  1950. client.DeleteFile(remoteFile);
  1951. }
  1952. }
  1953. }
  1954. }
  1955. [TestMethod]
  1956. public void Sftp_WriteAllLines_IEnumerable_Encoding_DirectoryDoesNotExist()
  1957. {
  1958. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1959. var encoding = GetRandomEncoding();
  1960. IEnumerable<string> linesToWrite = new[] { "Forever", "&", "\u0116ver" };
  1961. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1962. {
  1963. client.Connect();
  1964. if (client.Exists(remoteFile))
  1965. {
  1966. client.DeleteFile(remoteFile);
  1967. }
  1968. try
  1969. {
  1970. client.WriteAllLines(remoteFile, linesToWrite, encoding);
  1971. Assert.Fail();
  1972. }
  1973. catch (SftpPathNotFoundException ex)
  1974. {
  1975. Assert.IsNull(ex.InnerException);
  1976. Assert.AreEqual("No such file", ex.Message);
  1977. }
  1978. finally
  1979. {
  1980. if (client.Exists(remoteFile))
  1981. {
  1982. client.DeleteFile(remoteFile);
  1983. }
  1984. }
  1985. }
  1986. }
  1987. [TestMethod]
  1988. public void Sftp_WriteAllLines_IEnumerable_Encoding_ExistingFile()
  1989. {
  1990. var encoding = GetRandomEncoding();
  1991. const string initialContent = "\u0100ert & Ann Forever & Ever Lisa & Sofie";
  1992. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  1993. IEnumerable<string> linesToWrite1 = new[] { "Forever", "&", "\u0116ver" };
  1994. var linesToWrite1Bytes =
  1995. GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite1) + Environment.NewLine, encoding);
  1996. var expectedBytes1 = new ArrayBuilder<byte>().Add(linesToWrite1Bytes)
  1997. .Add(initialContentBytes,
  1998. linesToWrite1Bytes.Length,
  1999. initialContentBytes.Length - linesToWrite1Bytes.Length)
  2000. .Build();
  2001. IEnumerable<string> linesToWrite2 = new[] { "Forever", "&", "\u0116ver", "Gert & Ann", "Lisa + Sofie" };
  2002. var linesToWrite2Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite2) + Environment.NewLine, encoding);
  2003. var expectedBytes2 = linesToWrite2Bytes;
  2004. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2005. {
  2006. client.Connect();
  2007. var remoteFile = GenerateUniqueRemoteFileName();
  2008. if (client.Exists(remoteFile))
  2009. {
  2010. client.DeleteFile(remoteFile);
  2011. }
  2012. try
  2013. {
  2014. // create initial content
  2015. client.WriteAllText(remoteFile, initialContent, encoding);
  2016. #region Write less bytes than the current content, overwriting part of that content
  2017. client.WriteAllLines(remoteFile, linesToWrite1, encoding);
  2018. using (var fs = client.OpenRead(remoteFile))
  2019. {
  2020. var actualBytes = new byte[fs.Length];
  2021. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2022. Assert.IsTrue(expectedBytes1.IsEqualTo(actualBytes));
  2023. }
  2024. #endregion Write less bytes than the current content, overwriting part of that content
  2025. #region Write more bytes than the current content, overwriting and appending to that content
  2026. client.WriteAllLines(remoteFile, linesToWrite2, encoding);
  2027. using (var fs = client.OpenRead(remoteFile))
  2028. {
  2029. var actualBytes = new byte[fs.Length];
  2030. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2031. Assert.IsTrue(expectedBytes2.IsEqualTo(actualBytes));
  2032. }
  2033. #endregion Write more bytes than the current content, overwriting and appending to that content
  2034. }
  2035. finally
  2036. {
  2037. if (client.Exists(remoteFile))
  2038. {
  2039. client.DeleteFile(remoteFile);
  2040. }
  2041. }
  2042. }
  2043. }
  2044. [TestMethod]
  2045. public void Sftp_WriteAllLines_IEnumerable_Encoding_FileDoesNotExist()
  2046. {
  2047. var encoding = GetRandomEncoding();
  2048. IEnumerable<string> linesToWrite = new[] { "\u0139isa", "&", "Sofie" };
  2049. var linesToWriteBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite) + Environment.NewLine, encoding);
  2050. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2051. {
  2052. client.Connect();
  2053. var remoteFile = GenerateUniqueRemoteFileName();
  2054. if (client.Exists(remoteFile))
  2055. {
  2056. client.DeleteFile(remoteFile);
  2057. }
  2058. try
  2059. {
  2060. client.WriteAllLines(remoteFile, linesToWrite, encoding);
  2061. using (var fs = client.OpenRead(remoteFile))
  2062. {
  2063. var actualBytes = new byte[fs.Length];
  2064. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2065. Assert.IsTrue(linesToWriteBytes.IsEqualTo(actualBytes));
  2066. }
  2067. }
  2068. finally
  2069. {
  2070. if (client.Exists(remoteFile))
  2071. {
  2072. client.DeleteFile(remoteFile);
  2073. }
  2074. }
  2075. }
  2076. }
  2077. [TestMethod]
  2078. public void Sftp_WriteAllLines_Array_NoEncoding_DirectoryDoesNotExist()
  2079. {
  2080. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  2081. var linesToWrite = new[] { "Forever", "&", "\u0116ver" };
  2082. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2083. {
  2084. client.Connect();
  2085. if (client.Exists(remoteFile))
  2086. {
  2087. client.DeleteFile(remoteFile);
  2088. }
  2089. try
  2090. {
  2091. client.WriteAllLines(remoteFile, linesToWrite);
  2092. Assert.Fail();
  2093. }
  2094. catch (SftpPathNotFoundException ex)
  2095. {
  2096. Assert.IsNull(ex.InnerException);
  2097. Assert.AreEqual("No such file", ex.Message);
  2098. }
  2099. finally
  2100. {
  2101. if (client.Exists(remoteFile))
  2102. {
  2103. client.DeleteFile(remoteFile);
  2104. }
  2105. }
  2106. }
  2107. }
  2108. [TestMethod]
  2109. public void Sftp_WriteAllLines_Array_NoEncoding_ExistingFile()
  2110. {
  2111. var encoding = new UTF8Encoding(false, true);
  2112. const string initialContent = "\u0100ert & Ann Forever & Ever Lisa & Sofie";
  2113. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2114. var linesToWrite1 = new[] { "Forever", "&", "\u0116ver" };
  2115. var linesToWrite1Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite1) + Environment.NewLine, encoding);
  2116. var expectedBytes1 = new ArrayBuilder<byte>().Add(linesToWrite1Bytes)
  2117. .Add(initialContentBytes, linesToWrite1Bytes.Length, initialContentBytes.Length - linesToWrite1Bytes.Length)
  2118. .Build();
  2119. var linesToWrite2 = new[] { "Forever", "&", "\u0116ver", "Gert & Ann", "Lisa + Sofie" };
  2120. var linesToWrite2Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite2) + Environment.NewLine, encoding);
  2121. var expectedBytes2 = linesToWrite2Bytes;
  2122. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2123. {
  2124. client.Connect();
  2125. var remoteFile = GenerateUniqueRemoteFileName();
  2126. if (client.Exists(remoteFile))
  2127. {
  2128. client.DeleteFile(remoteFile);
  2129. }
  2130. try
  2131. {
  2132. // create initial content
  2133. client.WriteAllText(remoteFile, initialContent);
  2134. #region Write less bytes than the current content, overwriting part of that content
  2135. client.WriteAllLines(remoteFile, linesToWrite1);
  2136. using (var fs = client.OpenRead(remoteFile))
  2137. {
  2138. var actualBytes = new byte[fs.Length];
  2139. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2140. Assert.IsTrue(expectedBytes1.IsEqualTo(actualBytes));
  2141. }
  2142. #endregion Write less bytes than the current content, overwriting part of that content
  2143. #region Write more bytes than the current content, overwriting and appending to that content
  2144. client.WriteAllLines(remoteFile, linesToWrite2);
  2145. using (var fs = client.OpenRead(remoteFile))
  2146. {
  2147. var actualBytes = new byte[fs.Length];
  2148. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2149. Assert.IsTrue(expectedBytes2.IsEqualTo(actualBytes));
  2150. }
  2151. #endregion Write more bytes than the current content, overwriting and appending to that content
  2152. }
  2153. finally
  2154. {
  2155. if (client.Exists(remoteFile))
  2156. {
  2157. client.DeleteFile(remoteFile);
  2158. }
  2159. }
  2160. }
  2161. }
  2162. [TestMethod]
  2163. public void Sftp_WriteAllLines_Array_NoEncoding_FileDoesNotExist()
  2164. {
  2165. var encoding = new UTF8Encoding(false, true);
  2166. var linesToWrite = new[] { "\u0139isa", "&", "Sofie" };
  2167. var linesToWriteBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite) + Environment.NewLine, encoding);
  2168. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2169. {
  2170. client.Connect();
  2171. var remoteFile = GenerateUniqueRemoteFileName();
  2172. if (client.Exists(remoteFile))
  2173. {
  2174. client.DeleteFile(remoteFile);
  2175. }
  2176. try
  2177. {
  2178. client.WriteAllLines(remoteFile, linesToWrite);
  2179. using (var fs = client.OpenRead(remoteFile))
  2180. {
  2181. var actualBytes = new byte[fs.Length];
  2182. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2183. Assert.IsTrue(linesToWriteBytes.IsEqualTo(actualBytes));
  2184. }
  2185. }
  2186. finally
  2187. {
  2188. if (client.Exists(remoteFile))
  2189. {
  2190. client.DeleteFile(remoteFile);
  2191. }
  2192. }
  2193. }
  2194. }
  2195. [TestMethod]
  2196. public void Sftp_WriteAllLines_Array_Encoding_DirectoryDoesNotExist()
  2197. {
  2198. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  2199. var encoding = GetRandomEncoding();
  2200. var linesToWrite = new[] { "Forever", "&", "\u0116ver" };
  2201. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2202. {
  2203. client.Connect();
  2204. if (client.Exists(remoteFile))
  2205. {
  2206. client.DeleteFile(remoteFile);
  2207. }
  2208. try
  2209. {
  2210. client.WriteAllLines(remoteFile, linesToWrite, encoding);
  2211. Assert.Fail();
  2212. }
  2213. catch (SftpPathNotFoundException ex)
  2214. {
  2215. Assert.IsNull(ex.InnerException);
  2216. Assert.AreEqual("No such file", ex.Message);
  2217. }
  2218. finally
  2219. {
  2220. if (client.Exists(remoteFile))
  2221. {
  2222. client.DeleteFile(remoteFile);
  2223. }
  2224. }
  2225. }
  2226. }
  2227. [TestMethod]
  2228. public void Sftp_WriteAllLines_Array_Encoding_ExistingFile()
  2229. {
  2230. const string initialContent = "\u0100ert & Ann Forever & Ever Lisa & Sofie";
  2231. var encoding = GetRandomEncoding();
  2232. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2233. var linesToWrite1 = new[] { "Forever", "&", "\u0116ver" };
  2234. var linesToWrite1Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite1) + Environment.NewLine, encoding);
  2235. var expectedBytes1 = new ArrayBuilder<byte>().Add(linesToWrite1Bytes)
  2236. .Add(initialContentBytes, linesToWrite1Bytes.Length, initialContentBytes.Length - linesToWrite1Bytes.Length)
  2237. .Build();
  2238. var linesToWrite2 = new[] { "Forever", "&", "\u0116ver", "Gert & Ann", "Lisa + Sofie" };
  2239. var linesToWrite2Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite2) + Environment.NewLine, encoding);
  2240. var expectedBytes2 = linesToWrite2Bytes;
  2241. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2242. {
  2243. client.Connect();
  2244. var remoteFile = GenerateUniqueRemoteFileName();
  2245. if (client.Exists(remoteFile))
  2246. {
  2247. client.DeleteFile(remoteFile);
  2248. }
  2249. try
  2250. {
  2251. // create initial content
  2252. client.WriteAllText(remoteFile, initialContent, encoding);
  2253. #region Write less bytes than the current content, overwriting part of that content
  2254. client.WriteAllLines(remoteFile, linesToWrite1, encoding);
  2255. using (var fs = client.OpenRead(remoteFile))
  2256. {
  2257. var actualBytes = new byte[fs.Length];
  2258. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2259. Assert.IsTrue(expectedBytes1.IsEqualTo(actualBytes));
  2260. }
  2261. #endregion Write less bytes than the current content, overwriting part of that content
  2262. #region Write more bytes than the current content, overwriting and appending to that content
  2263. client.WriteAllLines(remoteFile, linesToWrite2, encoding);
  2264. using (var fs = client.OpenRead(remoteFile))
  2265. {
  2266. var actualBytes = new byte[fs.Length];
  2267. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2268. Assert.IsTrue(expectedBytes2.IsEqualTo(actualBytes));
  2269. }
  2270. #endregion Write more bytes than the current content, overwriting and appending to that content
  2271. }
  2272. finally
  2273. {
  2274. if (client.Exists(remoteFile))
  2275. {
  2276. client.DeleteFile(remoteFile);
  2277. }
  2278. }
  2279. }
  2280. }
  2281. [TestMethod]
  2282. public void Sftp_WriteAllLines_Array_Encoding_FileDoesNotExist()
  2283. {
  2284. var encoding = GetRandomEncoding();
  2285. var linesToWrite = new[] { "\u0139isa", "&", "Sofie" };
  2286. var linesToWriteBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite) + Environment.NewLine, encoding);
  2287. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2288. {
  2289. client.Connect();
  2290. var remoteFile = GenerateUniqueRemoteFileName();
  2291. if (client.Exists(remoteFile))
  2292. {
  2293. client.DeleteFile(remoteFile);
  2294. }
  2295. try
  2296. {
  2297. client.WriteAllLines(remoteFile, linesToWrite, encoding);
  2298. using (var fs = client.OpenRead(remoteFile))
  2299. {
  2300. var actualBytes = new byte[fs.Length];
  2301. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2302. Assert.IsTrue(linesToWriteBytes.IsEqualTo(actualBytes));
  2303. }
  2304. }
  2305. finally
  2306. {
  2307. if (client.Exists(remoteFile))
  2308. {
  2309. client.DeleteFile(remoteFile);
  2310. }
  2311. }
  2312. }
  2313. }
  2314. [TestMethod]
  2315. public void Sftp_WriteAllText_NoEncoding_DirectoryDoesNotExist()
  2316. {
  2317. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  2318. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2319. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2320. {
  2321. client.Connect();
  2322. if (client.Exists(remoteFile))
  2323. {
  2324. client.DeleteFile(remoteFile);
  2325. }
  2326. try
  2327. {
  2328. client.WriteAllText(remoteFile, initialContent);
  2329. Assert.Fail();
  2330. }
  2331. catch (SftpPathNotFoundException ex)
  2332. {
  2333. Assert.IsNull(ex.InnerException);
  2334. Assert.AreEqual("No such file", ex.Message);
  2335. }
  2336. finally
  2337. {
  2338. if (client.Exists(remoteFile))
  2339. {
  2340. client.DeleteFile(remoteFile);
  2341. }
  2342. }
  2343. }
  2344. }
  2345. [TestMethod]
  2346. public void Sftp_WriteAllText_NoEncoding_ExistingFile()
  2347. {
  2348. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2349. const string newContent1 = "For\u0116ver & Ever";
  2350. var encoding = new UTF8Encoding(false, true);
  2351. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2352. var newContent1Bytes = GetBytesWithPreamble(newContent1, encoding);
  2353. var expectedBytes1 = new ArrayBuilder<byte>().Add(newContent1Bytes)
  2354. .Add(initialContentBytes, newContent1Bytes.Length, initialContentBytes.Length - newContent1Bytes.Length)
  2355. .Build();
  2356. var newContent2 = "Sofie & Lisa For\u0116ver & Ever with \u0100ert & Ann";
  2357. var newContent2Bytes = GetBytesWithPreamble(newContent2, encoding);
  2358. var expectedBytes2 = newContent2Bytes;
  2359. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2360. {
  2361. client.Connect();
  2362. var remoteFile = GenerateUniqueRemoteFileName();
  2363. if (client.Exists(remoteFile))
  2364. {
  2365. client.DeleteFile(remoteFile);
  2366. }
  2367. try
  2368. {
  2369. client.WriteAllText(remoteFile, initialContent);
  2370. #region Write less bytes than the current content, overwriting part of that content
  2371. client.WriteAllText(remoteFile, newContent1);
  2372. using (var fs = client.OpenRead(remoteFile))
  2373. {
  2374. var actualBytes = new byte[fs.Length];
  2375. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2376. Assert.IsTrue(expectedBytes1.IsEqualTo(actualBytes));
  2377. }
  2378. #endregion Write less bytes than the current content, overwriting part of that content
  2379. #region Write more bytes than the current content, overwriting and appending to that content
  2380. client.WriteAllText(remoteFile, newContent2);
  2381. using (var fs = client.OpenRead(remoteFile))
  2382. {
  2383. var actualBytes = new byte[fs.Length];
  2384. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2385. Assert.IsTrue(expectedBytes2.IsEqualTo(actualBytes));
  2386. }
  2387. #endregion Write more bytes than the current content, overwriting and appending to that content
  2388. }
  2389. finally
  2390. {
  2391. if (client.Exists(remoteFile))
  2392. {
  2393. client.DeleteFile(remoteFile);
  2394. }
  2395. }
  2396. }
  2397. }
  2398. [TestMethod]
  2399. public void Sftp_WriteAllText_NoEncoding_FileDoesNotExist()
  2400. {
  2401. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2402. var encoding = new UTF8Encoding(false, true);
  2403. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2404. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2405. {
  2406. client.Connect();
  2407. var remoteFile = GenerateUniqueRemoteFileName();
  2408. if (client.Exists(remoteFile))
  2409. {
  2410. client.DeleteFile(remoteFile);
  2411. }
  2412. try
  2413. {
  2414. client.WriteAllText(remoteFile, initialContent);
  2415. using (var fs = client.OpenRead(remoteFile))
  2416. {
  2417. var actualBytes = new byte[fs.Length];
  2418. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2419. Assert.IsTrue(initialContentBytes.IsEqualTo(actualBytes));
  2420. }
  2421. }
  2422. finally
  2423. {
  2424. if (client.Exists(remoteFile))
  2425. {
  2426. client.DeleteFile(remoteFile);
  2427. }
  2428. }
  2429. }
  2430. }
  2431. [TestMethod]
  2432. public void Sftp_WriteAllText_Encoding_DirectoryDoesNotExist()
  2433. {
  2434. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  2435. var encoding = GetRandomEncoding();
  2436. const string content = "For\u0116ver & Ever";
  2437. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2438. {
  2439. client.Connect();
  2440. if (client.Exists(remoteFile))
  2441. {
  2442. client.DeleteFile(remoteFile);
  2443. }
  2444. try
  2445. {
  2446. client.WriteAllText(remoteFile, content, encoding);
  2447. Assert.Fail();
  2448. }
  2449. catch (SftpPathNotFoundException ex)
  2450. {
  2451. Assert.IsNull(ex.InnerException);
  2452. Assert.AreEqual("No such file", ex.Message);
  2453. }
  2454. finally
  2455. {
  2456. if (client.Exists(remoteFile))
  2457. {
  2458. client.DeleteFile(remoteFile);
  2459. }
  2460. }
  2461. }
  2462. }
  2463. [TestMethod]
  2464. public void Sftp_WriteAllText_Encoding_ExistingFile()
  2465. {
  2466. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2467. const string newContent1 = "For\u0116ver & Ever";
  2468. const string newContent2 = "Sofie & Lisa For\u0116ver & Ever with \u0100ert & Ann";
  2469. var encoding = GetRandomEncoding();
  2470. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2471. var newContent1Bytes = GetBytesWithPreamble(newContent1, encoding);
  2472. var expectedBytes1 = new ArrayBuilder<byte>().Add(newContent1Bytes)
  2473. .Add(initialContentBytes, newContent1Bytes.Length, initialContentBytes.Length - newContent1Bytes.Length)
  2474. .Build();
  2475. var newContent2Bytes = GetBytesWithPreamble(newContent2, encoding);
  2476. var expectedBytes2 = newContent2Bytes;
  2477. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2478. {
  2479. client.Connect();
  2480. var remoteFile = GenerateUniqueRemoteFileName();
  2481. if (client.Exists(remoteFile))
  2482. {
  2483. client.DeleteFile(remoteFile);
  2484. }
  2485. try
  2486. {
  2487. client.WriteAllText(remoteFile, initialContent, encoding);
  2488. #region Write less bytes than the current content, overwriting part of that content
  2489. client.WriteAllText(remoteFile, newContent1, encoding);
  2490. using (var fs = client.OpenRead(remoteFile))
  2491. {
  2492. var actualBytes = new byte[fs.Length];
  2493. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2494. Assert.IsTrue(expectedBytes1.IsEqualTo(actualBytes));
  2495. }
  2496. #endregion Write less bytes than the current content, overwriting part of that content
  2497. #region Write more bytes than the current content, overwriting and appending to that content
  2498. client.WriteAllText(remoteFile, newContent2, encoding);
  2499. using (var fs = client.OpenRead(remoteFile))
  2500. {
  2501. var actualBytes = new byte[fs.Length];
  2502. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2503. Assert.IsTrue(expectedBytes2.IsEqualTo(actualBytes));
  2504. }
  2505. #endregion Write more bytes than the current content, overwriting and appending to that content
  2506. }
  2507. finally
  2508. {
  2509. if (client.Exists(remoteFile))
  2510. {
  2511. client.DeleteFile(remoteFile);
  2512. }
  2513. }
  2514. }
  2515. }
  2516. [TestMethod]
  2517. public void Sftp_WriteAllText_Encoding_FileDoesNotExist()
  2518. {
  2519. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2520. var encoding = GetRandomEncoding();
  2521. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2522. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2523. {
  2524. client.Connect();
  2525. var remoteFile = GenerateUniqueRemoteFileName();
  2526. if (client.Exists(remoteFile))
  2527. {
  2528. client.DeleteFile(remoteFile);
  2529. }
  2530. try
  2531. {
  2532. client.WriteAllText(remoteFile, initialContent, encoding);
  2533. using (var fs = client.OpenRead(remoteFile))
  2534. {
  2535. var actualBytes = new byte[fs.Length];
  2536. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2537. Assert.IsTrue(initialContentBytes.IsEqualTo(actualBytes));
  2538. }
  2539. }
  2540. finally
  2541. {
  2542. if (client.Exists(remoteFile))
  2543. {
  2544. client.DeleteFile(remoteFile);
  2545. }
  2546. }
  2547. }
  2548. }
  2549. [TestMethod]
  2550. public void Sftp_BeginDownloadFile_FileDoesNotExist()
  2551. {
  2552. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2553. {
  2554. client.Connect();
  2555. var remoteFile = GenerateUniqueRemoteFileName();
  2556. if (client.Exists(remoteFile))
  2557. {
  2558. client.DeleteFile(remoteFile);
  2559. }
  2560. try
  2561. {
  2562. using (var ms = new MemoryStream())
  2563. {
  2564. var asyncResult = client.BeginDownloadFile(remoteFile, ms);
  2565. try
  2566. {
  2567. client.EndDownloadFile(asyncResult);
  2568. Assert.Fail();
  2569. }
  2570. catch (SftpPathNotFoundException ex)
  2571. {
  2572. Assert.IsNull(ex.InnerException);
  2573. Assert.AreEqual("No such file", ex.Message);
  2574. // ensure file was not created by us
  2575. Assert.IsFalse(client.Exists(remoteFile));
  2576. }
  2577. }
  2578. }
  2579. finally
  2580. {
  2581. if (client.Exists(remoteFile))
  2582. {
  2583. client.DeleteFile(remoteFile);
  2584. }
  2585. }
  2586. }
  2587. }
  2588. [TestMethod]
  2589. public void Sftp_BeginListDirectory_DirectoryDoesNotExist()
  2590. {
  2591. const string remoteDirectory = "/home/sshnet/test123";
  2592. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2593. {
  2594. client.Connect();
  2595. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  2596. {
  2597. command.Execute();
  2598. }
  2599. }
  2600. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2601. {
  2602. client.Connect();
  2603. var asyncResult = client.BeginListDirectory(remoteDirectory, null, null);
  2604. try
  2605. {
  2606. client.EndListDirectory(asyncResult);
  2607. Assert.Fail();
  2608. }
  2609. catch (SftpPathNotFoundException ex)
  2610. {
  2611. Assert.IsNull(ex.InnerException);
  2612. Assert.AreEqual("No such file", ex.Message);
  2613. // ensure directory was not created by us
  2614. Assert.IsFalse(client.Exists(remoteDirectory));
  2615. }
  2616. }
  2617. }
  2618. [TestMethod]
  2619. public void Sftp_BeginUploadFile_InputAndPath_DirectoryDoesNotExist()
  2620. {
  2621. const int size = 50 * 1024 * 1024;
  2622. const string remoteDirectory = "/home/sshnet/test123";
  2623. const string remoteFile = remoteDirectory + "/test";
  2624. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2625. {
  2626. client.Connect();
  2627. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  2628. {
  2629. command.Execute();
  2630. }
  2631. }
  2632. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2633. {
  2634. client.Connect();
  2635. var memoryStream = CreateMemoryStream(size);
  2636. memoryStream.Position = 0;
  2637. var asyncResult = client.BeginUploadFile(memoryStream, remoteFile);
  2638. try
  2639. {
  2640. client.EndUploadFile(asyncResult);
  2641. Assert.Fail();
  2642. }
  2643. catch (SftpPathNotFoundException)
  2644. {
  2645. }
  2646. }
  2647. }
  2648. [TestMethod]
  2649. public void Sftp_BeginUploadFile_InputAndPath_FileDoesNotExist()
  2650. {
  2651. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2652. {
  2653. client.Connect();
  2654. var remoteFile = GenerateUniqueRemoteFileName();
  2655. if (client.Exists(remoteFile))
  2656. {
  2657. client.DeleteFile(remoteFile);
  2658. }
  2659. try
  2660. {
  2661. var uploadMemoryStream = new MemoryStream();
  2662. var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8);
  2663. sw.Write("Gert & Ann");
  2664. sw.Flush();
  2665. uploadMemoryStream.Position = 0;
  2666. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile);
  2667. client.EndUploadFile(asyncResult);
  2668. using (var downloadMemoryStream = new MemoryStream())
  2669. {
  2670. client.DownloadFile(remoteFile, downloadMemoryStream);
  2671. downloadMemoryStream.Position = 0;
  2672. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2673. {
  2674. var content = sr.ReadToEnd();
  2675. Assert.AreEqual("Gert & Ann", content);
  2676. }
  2677. }
  2678. }
  2679. finally
  2680. {
  2681. if (client.Exists(remoteFile))
  2682. {
  2683. client.DeleteFile(remoteFile);
  2684. }
  2685. }
  2686. }
  2687. }
  2688. [TestMethod]
  2689. public void Sftp_BeginUploadFile_InputAndPath_ExistingFile()
  2690. {
  2691. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2692. {
  2693. client.Connect();
  2694. var remoteFile = GenerateUniqueRemoteFileName();
  2695. if (client.Exists(remoteFile))
  2696. {
  2697. client.DeleteFile(remoteFile);
  2698. }
  2699. try
  2700. {
  2701. client.WriteAllText(remoteFile, "Gert & Ann & Lisa");
  2702. var uploadMemoryStream = new MemoryStream();
  2703. var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8);
  2704. sw.Write("Ann & Gert");
  2705. sw.Flush();
  2706. uploadMemoryStream.Position = 0;
  2707. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile);
  2708. client.EndUploadFile(asyncResult);
  2709. using (var downloadMemoryStream = new MemoryStream())
  2710. {
  2711. client.DownloadFile(remoteFile, downloadMemoryStream);
  2712. downloadMemoryStream.Position = 0;
  2713. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2714. {
  2715. var content = sr.ReadToEnd();
  2716. Assert.AreEqual("Ann & Gert", content);
  2717. }
  2718. }
  2719. }
  2720. finally
  2721. {
  2722. if (client.Exists(remoteFile))
  2723. {
  2724. client.DeleteFile(remoteFile);
  2725. }
  2726. }
  2727. }
  2728. }
  2729. [TestMethod]
  2730. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsFalse_DirectoryDoesNotExist()
  2731. {
  2732. const int size = 50 * 1024 * 1024;
  2733. const string remoteDirectory = "/home/sshnet/test123";
  2734. const string remoteFile = remoteDirectory + "/test";
  2735. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2736. {
  2737. client.Connect();
  2738. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  2739. {
  2740. command.Execute();
  2741. }
  2742. }
  2743. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2744. {
  2745. client.Connect();
  2746. var memoryStream = CreateMemoryStream(size);
  2747. memoryStream.Position = 0;
  2748. var asyncResult = client.BeginUploadFile(memoryStream, remoteFile, false, null, null);
  2749. try
  2750. {
  2751. client.EndUploadFile(asyncResult);
  2752. Assert.Fail();
  2753. }
  2754. catch (SftpPathNotFoundException)
  2755. {
  2756. }
  2757. }
  2758. }
  2759. [TestMethod]
  2760. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsFalse_FileDoesNotExist()
  2761. {
  2762. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2763. {
  2764. client.Connect();
  2765. var remoteFile = GenerateUniqueRemoteFileName();
  2766. if (client.Exists(remoteFile))
  2767. {
  2768. client.DeleteFile(remoteFile);
  2769. }
  2770. try
  2771. {
  2772. using (var uploadMemoryStream = new MemoryStream())
  2773. using (var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8))
  2774. {
  2775. sw.Write("Gert & Ann");
  2776. sw.Flush();
  2777. uploadMemoryStream.Position = 0;
  2778. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile, false, null, null);
  2779. client.EndUploadFile(asyncResult);
  2780. }
  2781. using (var downloadMemoryStream = new MemoryStream())
  2782. {
  2783. client.DownloadFile(remoteFile, downloadMemoryStream);
  2784. downloadMemoryStream.Position = 0;
  2785. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2786. {
  2787. var content = sr.ReadToEnd();
  2788. Assert.AreEqual("Gert & Ann", content);
  2789. }
  2790. }
  2791. }
  2792. finally
  2793. {
  2794. if (client.Exists(remoteFile))
  2795. {
  2796. client.DeleteFile(remoteFile);
  2797. }
  2798. }
  2799. }
  2800. }
  2801. [TestMethod]
  2802. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsFalse_ExistingFile()
  2803. {
  2804. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2805. {
  2806. client.Connect();
  2807. var remoteFile = GenerateUniqueRemoteFileName();
  2808. if (client.Exists(remoteFile))
  2809. {
  2810. client.DeleteFile(remoteFile);
  2811. }
  2812. try
  2813. {
  2814. client.WriteAllText(remoteFile, "Gert & Ann & Lisa");
  2815. var uploadMemoryStream = new MemoryStream();
  2816. var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8);
  2817. sw.Write("Ann & Gert");
  2818. sw.Flush();
  2819. uploadMemoryStream.Position = 0;
  2820. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile, false, null, null);
  2821. try
  2822. {
  2823. client.EndUploadFile(asyncResult);
  2824. Assert.Fail();
  2825. }
  2826. catch (SshException ex)
  2827. {
  2828. Assert.AreEqual(typeof(SshException), ex.GetType());
  2829. Assert.IsNull(ex.InnerException);
  2830. Assert.AreEqual("Failure", ex.Message);
  2831. }
  2832. }
  2833. finally
  2834. {
  2835. if (client.Exists(remoteFile))
  2836. {
  2837. client.DeleteFile(remoteFile);
  2838. }
  2839. }
  2840. }
  2841. }
  2842. [TestMethod]
  2843. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsTrue_DirectoryDoesNotExist()
  2844. {
  2845. const int size = 50 * 1024 * 1024;
  2846. const string remoteDirectory = "/home/sshnet/test123";
  2847. const string remoteFile = remoteDirectory + "/test";
  2848. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2849. {
  2850. client.Connect();
  2851. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  2852. {
  2853. command.Execute();
  2854. }
  2855. }
  2856. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2857. {
  2858. client.Connect();
  2859. var memoryStream = CreateMemoryStream(size);
  2860. memoryStream.Position = 0;
  2861. var asyncResult = client.BeginUploadFile(memoryStream, remoteFile, true, null, null);
  2862. try
  2863. {
  2864. client.EndUploadFile(asyncResult);
  2865. Assert.Fail();
  2866. }
  2867. catch (SftpPathNotFoundException)
  2868. {
  2869. }
  2870. }
  2871. }
  2872. [TestMethod]
  2873. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsTrue_FileDoesNotExist()
  2874. {
  2875. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2876. {
  2877. client.Connect();
  2878. var remoteFile = GenerateUniqueRemoteFileName();
  2879. if (client.Exists(remoteFile))
  2880. {
  2881. client.DeleteFile(remoteFile);
  2882. }
  2883. try
  2884. {
  2885. using (var uploadMemoryStream = new MemoryStream())
  2886. using (var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8))
  2887. {
  2888. sw.Write("Gert & Ann");
  2889. sw.Flush();
  2890. uploadMemoryStream.Position = 0;
  2891. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile, true, null, null);
  2892. client.EndUploadFile(asyncResult);
  2893. }
  2894. using (var downloadMemoryStream = new MemoryStream())
  2895. {
  2896. client.DownloadFile(remoteFile, downloadMemoryStream);
  2897. downloadMemoryStream.Position = 0;
  2898. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2899. {
  2900. var content = sr.ReadToEnd();
  2901. Assert.AreEqual("Gert & Ann", content);
  2902. }
  2903. }
  2904. }
  2905. finally
  2906. {
  2907. if (client.Exists(remoteFile))
  2908. {
  2909. client.DeleteFile(remoteFile);
  2910. }
  2911. }
  2912. }
  2913. }
  2914. [TestMethod]
  2915. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsTrue_ExistingFile()
  2916. {
  2917. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2918. {
  2919. client.Connect();
  2920. var remoteFile = GenerateUniqueRemoteFileName();
  2921. if (client.Exists(remoteFile))
  2922. {
  2923. client.DeleteFile(remoteFile);
  2924. }
  2925. try
  2926. {
  2927. client.WriteAllText(remoteFile, "Gert & Ann & Lisa");
  2928. using (var uploadMemoryStream = new MemoryStream())
  2929. using (var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8))
  2930. {
  2931. sw.Write("Ann & Gert");
  2932. sw.Flush();
  2933. uploadMemoryStream.Position = 0;
  2934. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile, true, null, null);
  2935. client.EndUploadFile(asyncResult);
  2936. }
  2937. using (var downloadMemoryStream = new MemoryStream())
  2938. {
  2939. client.DownloadFile(remoteFile, downloadMemoryStream);
  2940. downloadMemoryStream.Position = 0;
  2941. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2942. {
  2943. var content = sr.ReadToEnd();
  2944. Assert.AreEqual("Ann & Gert", content);
  2945. }
  2946. }
  2947. }
  2948. finally
  2949. {
  2950. if (client.Exists(remoteFile))
  2951. {
  2952. client.DeleteFile(remoteFile);
  2953. }
  2954. }
  2955. }
  2956. }
  2957. [TestMethod]
  2958. public void Sftp_UploadAndDownloadBigFile()
  2959. {
  2960. const int size = 50 * 1024 * 1024;
  2961. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2962. {
  2963. client.Connect();
  2964. var remoteFile = GenerateUniqueRemoteFileName();
  2965. if (client.Exists(remoteFile))
  2966. {
  2967. client.Delete(remoteFile);
  2968. }
  2969. try
  2970. {
  2971. var memoryStream = CreateMemoryStream(size);
  2972. memoryStream.Position = 0;
  2973. client.UploadFile(memoryStream, remoteFile);
  2974. var stopwatch = new Stopwatch();
  2975. stopwatch.Start();
  2976. // check uploaded file
  2977. memoryStream = new MemoryStream();
  2978. client.DownloadFile(remoteFile, memoryStream);
  2979. Assert.AreEqual(size, memoryStream.Length);
  2980. stopwatch.Stop();
  2981. Console.WriteLine(@"Elapsed: {0} ms", stopwatch.ElapsedMilliseconds);
  2982. Console.WriteLine(@"Transfer speed: {0:N2} KB/s",
  2983. CalculateTransferSpeed(memoryStream.Length, stopwatch.ElapsedMilliseconds));
  2984. }
  2985. finally
  2986. {
  2987. if (client.Exists(remoteFile))
  2988. {
  2989. client.Delete(remoteFile);
  2990. }
  2991. }
  2992. }
  2993. }
  2994. /// <summary>
  2995. /// Issue 1672
  2996. /// </summary>
  2997. [TestMethod]
  2998. public void Sftp_CurrentWorkingDirectory()
  2999. {
  3000. const string homeDirectory = "/home/sshnet";
  3001. const string otherDirectory = homeDirectory + "/dir";
  3002. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3003. {
  3004. client.Connect();
  3005. if (client.Exists(otherDirectory))
  3006. {
  3007. client.DeleteDirectory(otherDirectory);
  3008. }
  3009. try
  3010. {
  3011. client.CreateDirectory(otherDirectory);
  3012. client.ChangeDirectory(otherDirectory);
  3013. using (var s = CreateStreamWithContent("A"))
  3014. {
  3015. client.UploadFile(s, "a.txt");
  3016. }
  3017. using (var s = new MemoryStream())
  3018. {
  3019. client.DownloadFile("a.txt", s);
  3020. s.Position = 0;
  3021. var content = Encoding.ASCII.GetString(s.ToArray());
  3022. Assert.AreEqual("A", content);
  3023. }
  3024. Assert.IsTrue(client.Exists(otherDirectory + "/a.txt"));
  3025. client.DeleteFile("a.txt");
  3026. Assert.IsFalse(client.Exists(otherDirectory + "/a.txt"));
  3027. client.DeleteDirectory(".");
  3028. Assert.IsFalse(client.Exists(otherDirectory));
  3029. }
  3030. finally
  3031. {
  3032. if (client.Exists(otherDirectory))
  3033. {
  3034. client.DeleteDirectory(otherDirectory);
  3035. }
  3036. }
  3037. }
  3038. }
  3039. [TestMethod]
  3040. public void Sftp_Exists()
  3041. {
  3042. const string remoteHome = "/home/sshnet";
  3043. #region Setup
  3044. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3045. {
  3046. client.Connect();
  3047. #region Clean-up
  3048. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/DoesNotExist"}"))
  3049. {
  3050. command.Execute();
  3051. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3052. }
  3053. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.directory.exists"}"))
  3054. {
  3055. command.Execute();
  3056. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3057. }
  3058. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/directory.exists"}")
  3059. )
  3060. {
  3061. command.Execute();
  3062. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3063. }
  3064. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.file.exists"}"))
  3065. {
  3066. command.Execute();
  3067. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3068. }
  3069. using (var command = client.CreateCommand($"rm -f {remoteHome + "/file.exists"}"))
  3070. {
  3071. command.Execute();
  3072. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3073. }
  3074. #endregion Clean-up
  3075. #region Setup
  3076. using (var command = client.CreateCommand($"touch {remoteHome + "/file.exists"}"))
  3077. {
  3078. command.Execute();
  3079. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3080. }
  3081. using (var command = client.CreateCommand($"mkdir {remoteHome + "/directory.exists"}"))
  3082. {
  3083. command.Execute();
  3084. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3085. }
  3086. using (var command = client.CreateCommand($"ln -s {remoteHome + "/file.exists"} {remoteHome + "/symlink.to.file.exists"}"))
  3087. {
  3088. command.Execute();
  3089. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3090. }
  3091. using (var command = client.CreateCommand($"ln -s {remoteHome + "/directory.exists"} {remoteHome + "/symlink.to.directory.exists"}"))
  3092. {
  3093. command.Execute();
  3094. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3095. }
  3096. #endregion Setup
  3097. }
  3098. #endregion Setup
  3099. #region Assert
  3100. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3101. {
  3102. client.Connect();
  3103. Assert.IsFalse(client.Exists(remoteHome + "/DoesNotExist"));
  3104. Assert.IsTrue(client.Exists(remoteHome + "/file.exists"));
  3105. Assert.IsTrue(client.Exists(remoteHome + "/symlink.to.file.exists"));
  3106. Assert.IsTrue(client.Exists(remoteHome + "/directory.exists"));
  3107. Assert.IsTrue(client.Exists(remoteHome + "/symlink.to.directory.exists"));
  3108. }
  3109. #endregion Assert
  3110. #region Teardown
  3111. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3112. {
  3113. client.Connect();
  3114. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/DoesNotExist"}"))
  3115. {
  3116. command.Execute();
  3117. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3118. }
  3119. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.directory.exists"}"))
  3120. {
  3121. command.Execute();
  3122. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3123. }
  3124. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/directory.exists"}"))
  3125. {
  3126. command.Execute();
  3127. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3128. }
  3129. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.file.exists"}"))
  3130. {
  3131. command.Execute();
  3132. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3133. }
  3134. using (var command = client.CreateCommand($"rm -f {remoteHome + "/file.exists"}"))
  3135. {
  3136. command.Execute();
  3137. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3138. }
  3139. }
  3140. #endregion Teardown
  3141. }
  3142. [TestMethod]
  3143. public void Sftp_ListDirectory()
  3144. {
  3145. const string remoteDirectory = "/home/sshnet/test123";
  3146. try
  3147. {
  3148. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3149. {
  3150. client.Connect();
  3151. client.RunCommand($@"rm -Rf ""{remoteDirectory}""");
  3152. client.RunCommand($@"mkdir -p ""{remoteDirectory}""");
  3153. client.RunCommand($@"mkdir -p ""{remoteDirectory}/sub""");
  3154. client.RunCommand($@"touch ""{remoteDirectory}/file1""");
  3155. client.RunCommand($@"touch ""{remoteDirectory}/file2""");
  3156. }
  3157. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3158. {
  3159. client.Connect();
  3160. client.ChangeDirectory(remoteDirectory);
  3161. var directoryContent = client.ListDirectory(".").OrderBy(p => p.Name).ToList();
  3162. Assert.AreEqual(5, directoryContent.Count);
  3163. Assert.AreEqual(".", directoryContent[0].Name);
  3164. Assert.AreEqual($"{remoteDirectory}/.", directoryContent[0].FullName);
  3165. Assert.IsTrue(directoryContent[0].IsDirectory);
  3166. Assert.AreEqual("..", directoryContent[1].Name);
  3167. Assert.AreEqual($"{remoteDirectory}/..", directoryContent[1].FullName);
  3168. Assert.IsTrue(directoryContent[1].IsDirectory);
  3169. Assert.AreEqual("file1", directoryContent[2].Name);
  3170. Assert.AreEqual($"{remoteDirectory}/file1", directoryContent[2].FullName);
  3171. Assert.IsFalse(directoryContent[2].IsDirectory);
  3172. Assert.AreEqual("file2", directoryContent[3].Name);
  3173. Assert.AreEqual($"{remoteDirectory}/file2", directoryContent[3].FullName);
  3174. Assert.IsFalse(directoryContent[3].IsDirectory);
  3175. Assert.AreEqual("sub", directoryContent[4].Name);
  3176. Assert.AreEqual($"{remoteDirectory}/sub", directoryContent[4].FullName);
  3177. Assert.IsTrue(directoryContent[4].IsDirectory);
  3178. }
  3179. }
  3180. finally
  3181. {
  3182. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3183. {
  3184. client.Connect();
  3185. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3186. {
  3187. command.Execute();
  3188. }
  3189. }
  3190. }
  3191. }
  3192. [TestMethod]
  3193. public void Sftp_ChangeDirectory_DirectoryDoesNotExist()
  3194. {
  3195. const string remoteDirectory = "/home/sshnet/test123";
  3196. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3197. {
  3198. client.Connect();
  3199. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3200. {
  3201. command.Execute();
  3202. }
  3203. }
  3204. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3205. {
  3206. client.Connect();
  3207. try
  3208. {
  3209. client.ChangeDirectory(remoteDirectory);
  3210. Assert.Fail();
  3211. }
  3212. catch (SftpPathNotFoundException)
  3213. {
  3214. }
  3215. }
  3216. }
  3217. [TestMethod]
  3218. public void Sftp_ChangeDirectory_DirectoryExists()
  3219. {
  3220. const string remoteDirectory = "/home/sshnet/test123";
  3221. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3222. {
  3223. client.Connect();
  3224. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3225. {
  3226. command.Execute();
  3227. }
  3228. using (var command = client.CreateCommand("mkdir -p " + _remotePathTransformation.Transform(remoteDirectory)))
  3229. {
  3230. command.Execute();
  3231. }
  3232. }
  3233. try
  3234. {
  3235. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3236. {
  3237. client.Connect();
  3238. client.ChangeDirectory(remoteDirectory);
  3239. Assert.AreEqual(remoteDirectory, client.WorkingDirectory);
  3240. using (var uploadStream = CreateMemoryStream(100))
  3241. {
  3242. uploadStream.Position = 0;
  3243. client.UploadFile(uploadStream, "gert.txt");
  3244. uploadStream.Position = 0;
  3245. using (var downloadStream = client.OpenRead(remoteDirectory + "/gert.txt"))
  3246. {
  3247. Assert.AreEqual(CreateHash(uploadStream), CreateHash(downloadStream));
  3248. }
  3249. }
  3250. }
  3251. }
  3252. finally
  3253. {
  3254. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3255. {
  3256. client.Connect();
  3257. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3258. {
  3259. command.Execute();
  3260. }
  3261. }
  3262. }
  3263. }
  3264. [TestMethod]
  3265. public void Sftp_DownloadFile_MemoryStream()
  3266. {
  3267. const int fileSize = 500 * 1024;
  3268. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3269. {
  3270. client.Connect();
  3271. var remoteFile = GenerateUniqueRemoteFileName();
  3272. SftpCreateRemoteFile(client, remoteFile, fileSize);
  3273. try
  3274. {
  3275. using (var memoryStream = new MemoryStream())
  3276. {
  3277. var stopwatch = new Stopwatch();
  3278. stopwatch.Start();
  3279. client.DownloadFile(remoteFile, memoryStream);
  3280. stopwatch.Stop();
  3281. var transferSpeed = CalculateTransferSpeed(memoryStream.Length, stopwatch.ElapsedMilliseconds);
  3282. Console.WriteLine(@"Elapsed: {0} ms", stopwatch.ElapsedMilliseconds);
  3283. Console.WriteLine(@"Transfer speed: {0:N2} KB/s", transferSpeed);
  3284. Assert.AreEqual(fileSize, memoryStream.Length);
  3285. }
  3286. }
  3287. finally
  3288. {
  3289. if (client.Exists(remoteFile))
  3290. {
  3291. client.DeleteFile(remoteFile);
  3292. }
  3293. }
  3294. }
  3295. }
  3296. [TestMethod]
  3297. public void Sftp_SubsystemExecution_Failed()
  3298. {
  3299. var remoteSshdConfig = new RemoteSshd(_adminConnectionInfoFactory).OpenConfig();
  3300. // Disable SFTP subsystem
  3301. remoteSshdConfig.ClearSubsystems()
  3302. .Update()
  3303. .Restart();
  3304. var remoteSshdReconfiguredToDefaultState = false;
  3305. try
  3306. {
  3307. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3308. {
  3309. try
  3310. {
  3311. client.Connect();
  3312. Assert.Fail("Establishing SFTP connection should have failed.");
  3313. }
  3314. catch (SshException ex)
  3315. {
  3316. Assert.IsNull(ex.InnerException);
  3317. Assert.AreEqual("Subsystem 'sftp' could not be executed.", ex.Message);
  3318. }
  3319. // Re-enable SFTP subsystem
  3320. remoteSshdConfig.Reset();
  3321. remoteSshdReconfiguredToDefaultState = true;
  3322. // ensure we can reconnect the same SftpClient instance
  3323. client.Connect();
  3324. // ensure SFTP session is correctly established
  3325. Assert.IsTrue(client.Exists("."));
  3326. }
  3327. }
  3328. finally
  3329. {
  3330. if (!remoteSshdReconfiguredToDefaultState)
  3331. {
  3332. remoteSshdConfig.Reset();
  3333. }
  3334. }
  3335. }
  3336. [TestMethod]
  3337. public void Sftp_SftpFileStream_ReadAndWrite()
  3338. {
  3339. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3340. {
  3341. client.Connect();
  3342. var remoteFile = GenerateUniqueRemoteFileName();
  3343. if (client.Exists(remoteFile))
  3344. {
  3345. client.DeleteFile(remoteFile);
  3346. }
  3347. try
  3348. {
  3349. using (var s = client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write))
  3350. {
  3351. s.Write(new byte[] { 5, 4, 3, 2, 1 }, 1, 3);
  3352. }
  3353. // switch from read to write mode
  3354. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3355. {
  3356. Assert.AreEqual(4, s.ReadByte());
  3357. Assert.AreEqual(3, s.ReadByte());
  3358. Assert.AreEqual(2, s.Position);
  3359. s.WriteByte(7);
  3360. s.Write(new byte[] { 8, 9, 10, 11, 12 }, 1, 3);
  3361. Assert.AreEqual(6, s.Position);
  3362. }
  3363. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3364. {
  3365. Assert.AreEqual(6, s.Length);
  3366. var buffer = new byte[s.Length];
  3367. Assert.AreEqual(6, s.Read(buffer, offset: 0, buffer.Length));
  3368. CollectionAssert.AreEqual(new byte[] { 4, 3, 7, 9, 10, 11 }, buffer);
  3369. // Ensure we've reached end of the stream
  3370. Assert.AreEqual(-1, s.ReadByte());
  3371. }
  3372. // switch from read to write mode, and back to read mode and finally
  3373. // append a byte
  3374. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3375. {
  3376. Assert.AreEqual(4, s.ReadByte());
  3377. Assert.AreEqual(3, s.ReadByte());
  3378. Assert.AreEqual(7, s.ReadByte());
  3379. s.Write(new byte[] { 0, 1, 6, 4 }, 1, 2);
  3380. Assert.AreEqual(11, s.ReadByte());
  3381. // Ensure we've reached end of the stream
  3382. Assert.AreEqual(-1, s.ReadByte());
  3383. s.WriteByte(12);
  3384. }
  3385. // switch from write to read mode, and back to write mode
  3386. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3387. {
  3388. s.WriteByte(5);
  3389. Assert.AreEqual(3, s.ReadByte());
  3390. s.WriteByte(13);
  3391. Assert.AreEqual(3, s.Position);
  3392. }
  3393. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3394. {
  3395. Assert.AreEqual(7, s.Length);
  3396. var buffer = new byte[s.Length];
  3397. Assert.AreEqual(7, s.Read(buffer, offset: 0, buffer.Length));
  3398. CollectionAssert.AreEqual(new byte[] { 5, 3, 13, 1, 6, 11, 12 }, buffer);
  3399. // Ensure we've reached end of the stream
  3400. Assert.AreEqual(-1, s.ReadByte());
  3401. }
  3402. }
  3403. finally
  3404. {
  3405. if (client.Exists(remoteFile))
  3406. {
  3407. client.DeleteFile(remoteFile);
  3408. }
  3409. }
  3410. }
  3411. }
  3412. [TestMethod]
  3413. public void Sftp_SftpFileStream_SetLength_ReduceLength()
  3414. {
  3415. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3416. {
  3417. client.Connect();
  3418. var remoteFile = GenerateUniqueRemoteFileName();
  3419. if (client.Exists(remoteFile))
  3420. {
  3421. client.DeleteFile(remoteFile);
  3422. }
  3423. try
  3424. {
  3425. using (var s = client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write))
  3426. {
  3427. s.Write(new byte[] { 5, 4, 3, 2, 1 }, 1, 3);
  3428. }
  3429. // reduce length while in write mode, with data in write buffer, and before
  3430. // current position
  3431. using (var s = client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  3432. {
  3433. s.Position = 3;
  3434. s.Write(new byte[] { 6, 7, 8, 9 }, offset: 0, count: 4);
  3435. Assert.AreEqual(7, s.Position);
  3436. // verify buffer has not yet been flushed
  3437. using (var fs = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3438. {
  3439. Assert.AreEqual(4, fs.ReadByte());
  3440. Assert.AreEqual(3, fs.ReadByte());
  3441. Assert.AreEqual(2, fs.ReadByte());
  3442. // Ensure we've reached end of the stream
  3443. Assert.AreEqual(-1, fs.ReadByte());
  3444. }
  3445. s.SetLength(5);
  3446. Assert.AreEqual(5, s.Position);
  3447. // verify that buffer was flushed and size has been modified
  3448. using (var fs = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3449. {
  3450. Assert.AreEqual(4, fs.ReadByte());
  3451. Assert.AreEqual(3, fs.ReadByte());
  3452. Assert.AreEqual(2, fs.ReadByte());
  3453. Assert.AreEqual(6, fs.ReadByte());
  3454. Assert.AreEqual(7, fs.ReadByte());
  3455. // Ensure we've reached end of the stream
  3456. Assert.AreEqual(-1, fs.ReadByte());
  3457. }
  3458. s.WriteByte(1);
  3459. }
  3460. // verify that last byte was correctly written to the file
  3461. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3462. {
  3463. Assert.AreEqual(6, s.Length);
  3464. var buffer = new byte[s.Length + 2];
  3465. Assert.AreEqual(6, s.Read(buffer, offset: 0, buffer.Length));
  3466. CollectionAssert.AreEqual(new byte[] { 4, 3, 2, 6, 7, 1, 0, 0 }, buffer);
  3467. // Ensure we've reached end of the stream
  3468. Assert.AreEqual(-1, s.ReadByte());
  3469. }
  3470. // reduce length while in read mode, but beyond current position
  3471. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3472. {
  3473. var buffer = new byte[1];
  3474. Assert.AreEqual(1, s.Read(buffer, offset: 0, buffer.Length));
  3475. CollectionAssert.AreEqual(new byte[] { 4 }, buffer);
  3476. s.SetLength(3);
  3477. using (var w = client.Open(remoteFile, FileMode.Open, FileAccess.Write))
  3478. {
  3479. w.Write(new byte[] { 8, 1, 6, 2 }, offset: 0, count: 4);
  3480. }
  3481. // verify that position was not changed
  3482. Assert.AreEqual(1, s.Position);
  3483. // verify that read buffer was cleared
  3484. Assert.AreEqual(1, s.ReadByte());
  3485. Assert.AreEqual(6, s.ReadByte());
  3486. Assert.AreEqual(2, s.ReadByte());
  3487. // Ensure we've reached end of the stream
  3488. Assert.AreEqual(-1, s.ReadByte());
  3489. Assert.AreEqual(4, s.Length);
  3490. }
  3491. // reduce length while in read mode, but before current position
  3492. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3493. {
  3494. var buffer = new byte[4];
  3495. Assert.AreEqual(4, s.Read(buffer, offset: 0, buffer.Length));
  3496. CollectionAssert.AreEqual(new byte[] { 8, 1, 6, 2 }, buffer);
  3497. Assert.AreEqual(4, s.Position);
  3498. s.SetLength(3);
  3499. // verify that position was moved to last byte
  3500. Assert.AreEqual(3, s.Position);
  3501. using (var w = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3502. {
  3503. Assert.AreEqual(3, w.Length);
  3504. Assert.AreEqual(8, w.ReadByte());
  3505. Assert.AreEqual(1, w.ReadByte());
  3506. Assert.AreEqual(6, w.ReadByte());
  3507. // Ensure we've reached end of the stream
  3508. Assert.AreEqual(-1, w.ReadByte());
  3509. }
  3510. // Ensure we've reached end of the stream
  3511. Assert.AreEqual(-1, s.ReadByte());
  3512. }
  3513. }
  3514. finally
  3515. {
  3516. if (client.Exists(remoteFile))
  3517. {
  3518. client.DeleteFile(remoteFile);
  3519. }
  3520. }
  3521. }
  3522. }
  3523. [TestMethod]
  3524. public void Sftp_SftpFileStream_Seek_BeyondEndOfFile_SeekOriginBegin()
  3525. {
  3526. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3527. {
  3528. client.BufferSize = 500;
  3529. client.Connect();
  3530. var remoteFile = GenerateUniqueRemoteFileName();
  3531. if (client.Exists(remoteFile))
  3532. {
  3533. client.DeleteFile(remoteFile);
  3534. }
  3535. try
  3536. {
  3537. // create single-byte file
  3538. using (var fs = client.OpenWrite(remoteFile))
  3539. {
  3540. fs.WriteByte(0x04);
  3541. }
  3542. // seek beyond EOF but not beyond buffer size
  3543. // do not write anything
  3544. using (var fs = client.OpenWrite(remoteFile))
  3545. {
  3546. var newPosition = fs.Seek(offset: 3L, SeekOrigin.Begin);
  3547. Assert.AreEqual(3, newPosition);
  3548. Assert.AreEqual(3, fs.Position);
  3549. }
  3550. using (var fs = client.OpenRead(remoteFile))
  3551. {
  3552. Assert.AreEqual(1, fs.Length);
  3553. Assert.AreEqual(0x04, fs.ReadByte());
  3554. // Ensure we've reached end of the stream
  3555. Assert.AreEqual(-1, fs.ReadByte());
  3556. }
  3557. client.DeleteFile(remoteFile);
  3558. // create single-byte file
  3559. using (var fs = client.OpenWrite(remoteFile))
  3560. {
  3561. fs.WriteByte(0x04);
  3562. }
  3563. // seek beyond EOF and beyond buffer size
  3564. // do not write anything
  3565. using (var fs = client.OpenWrite(remoteFile))
  3566. {
  3567. var newPosition = fs.Seek(offset: 700L, SeekOrigin.Begin);
  3568. Assert.AreEqual(700, newPosition);
  3569. Assert.AreEqual(700, fs.Position);
  3570. }
  3571. using (var fs = client.OpenRead(remoteFile))
  3572. {
  3573. Assert.AreEqual(1, fs.Length);
  3574. Assert.AreEqual(0x04, fs.ReadByte());
  3575. // Ensure we've reached end of the stream
  3576. Assert.AreEqual(-1, fs.ReadByte());
  3577. }
  3578. client.DeleteFile(remoteFile);
  3579. // create single-byte file
  3580. using (var fs = client.OpenWrite(remoteFile))
  3581. {
  3582. fs.WriteByte(0x04);
  3583. }
  3584. // seek beyond EOF but not beyond buffer size
  3585. // write less bytes than buffer size
  3586. var seekOffset = 3L;
  3587. // buffer holding the data that we'll write to the file
  3588. var writeBuffer = GenerateRandom(size: 7);
  3589. using (var fs = client.OpenWrite(remoteFile))
  3590. {
  3591. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  3592. Assert.AreEqual(seekOffset, newPosition);
  3593. Assert.AreEqual(seekOffset, fs.Position);
  3594. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3595. }
  3596. using (var fs = client.OpenRead(remoteFile))
  3597. {
  3598. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  3599. Assert.AreEqual(0x04, fs.ReadByte());
  3600. var soughtOverReadBufferffer = new byte[seekOffset - 1];
  3601. Assert.AreEqual(soughtOverReadBufferffer.Length, fs.Read(soughtOverReadBufferffer, offset: 0, soughtOverReadBufferffer.Length));
  3602. Assert.IsTrue(new byte[soughtOverReadBufferffer.Length].IsEqualTo(soughtOverReadBufferffer));
  3603. var readBuffer = new byte[writeBuffer.Length];
  3604. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3605. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3606. // Ensure we've reached end of the stream
  3607. Assert.AreEqual(-1, fs.ReadByte());
  3608. }
  3609. client.DeleteFile(remoteFile);
  3610. // create single-byte file
  3611. using (var fs = client.OpenWrite(remoteFile))
  3612. {
  3613. fs.WriteByte(0x04);
  3614. }
  3615. // seek beyond EOF and beyond buffer size
  3616. // write less bytes than buffer size
  3617. seekOffset = 700L;
  3618. // buffer holding the data that we'll write to the file
  3619. writeBuffer = GenerateRandom(size: 4);
  3620. using (var fs = client.OpenWrite(remoteFile))
  3621. {
  3622. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  3623. Assert.AreEqual(seekOffset, newPosition);
  3624. Assert.AreEqual(seekOffset, fs.Position);
  3625. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3626. }
  3627. using (var fs = client.OpenRead(remoteFile))
  3628. {
  3629. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  3630. Assert.AreEqual(0x04, fs.ReadByte());
  3631. var soughtOverReadBufferffer = new byte[seekOffset - 1];
  3632. Assert.AreEqual(soughtOverReadBufferffer.Length, fs.Read(soughtOverReadBufferffer, offset: 0, soughtOverReadBufferffer.Length));
  3633. Assert.IsTrue(new byte[soughtOverReadBufferffer.Length].IsEqualTo(soughtOverReadBufferffer));
  3634. var readBuffer = new byte[writeBuffer.Length];
  3635. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3636. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3637. // Ensure we've reached end of the stream
  3638. Assert.AreEqual(-1, fs.ReadByte());
  3639. }
  3640. client.DeleteFile(remoteFile);
  3641. // create single-byte file
  3642. using (var fs = client.OpenWrite(remoteFile))
  3643. {
  3644. fs.WriteByte(0x04);
  3645. }
  3646. // seek beyond EOF but not beyond buffer size
  3647. // write more bytes than buffer size
  3648. writeBuffer = GenerateRandom(size: 600);
  3649. using (var fs = client.OpenWrite(remoteFile))
  3650. {
  3651. var newPosition = fs.Seek(offset: 3L, SeekOrigin.Begin);
  3652. Assert.AreEqual(3, newPosition);
  3653. Assert.AreEqual(3, fs.Position);
  3654. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3655. }
  3656. using (var fs = client.OpenRead(remoteFile))
  3657. {
  3658. Assert.AreEqual(3 + writeBuffer.Length, fs.Length);
  3659. Assert.AreEqual(0x04, fs.ReadByte());
  3660. Assert.AreEqual(0x00, fs.ReadByte());
  3661. Assert.AreEqual(0x00, fs.ReadByte());
  3662. var readBuffer = new byte[writeBuffer.Length];
  3663. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3664. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3665. // Ensure we've reached end of the stream
  3666. Assert.AreEqual(-1, fs.ReadByte());
  3667. }
  3668. client.DeleteFile(remoteFile);
  3669. // create single-byte file
  3670. using (var fs = client.OpenWrite(remoteFile))
  3671. {
  3672. fs.WriteByte(0x04);
  3673. }
  3674. // seek beyond EOF and beyond buffer size
  3675. // write more bytes than buffer size
  3676. writeBuffer = GenerateRandom(size: 600);
  3677. using (var fs = client.OpenWrite(remoteFile))
  3678. {
  3679. var newPosition = fs.Seek(offset: 550, SeekOrigin.Begin);
  3680. Assert.AreEqual(550, newPosition);
  3681. Assert.AreEqual(550, fs.Position);
  3682. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3683. }
  3684. using (var fs = client.OpenRead(remoteFile))
  3685. {
  3686. Assert.AreEqual(550 + writeBuffer.Length, fs.Length);
  3687. Assert.AreEqual(0x04, fs.ReadByte());
  3688. var soughtOverReadBuffer = new byte[550 - 1];
  3689. Assert.AreEqual(550 - 1, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  3690. Assert.IsTrue(new byte[550 - 1].IsEqualTo(soughtOverReadBuffer));
  3691. var readBuffer = new byte[writeBuffer.Length];
  3692. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3693. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3694. // Ensure we've reached end of the stream
  3695. Assert.AreEqual(-1, fs.ReadByte());
  3696. }
  3697. }
  3698. finally
  3699. {
  3700. if (client.Exists(remoteFile))
  3701. {
  3702. client.DeleteFile(remoteFile);
  3703. }
  3704. }
  3705. }
  3706. }
  3707. [TestMethod]
  3708. public void Sftp_SftpFileStream_Seek_BeyondEndOfFile_SeekOriginEnd()
  3709. {
  3710. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3711. {
  3712. client.BufferSize = 500;
  3713. client.Connect();
  3714. var remoteFile = GenerateUniqueRemoteFileName();
  3715. if (client.Exists(remoteFile))
  3716. {
  3717. client.DeleteFile(remoteFile);
  3718. }
  3719. try
  3720. {
  3721. // create single-byte file
  3722. using (var fs = client.OpenWrite(remoteFile))
  3723. {
  3724. fs.WriteByte(0x04);
  3725. }
  3726. // seek beyond EOF but not beyond buffer size
  3727. // do not write anything
  3728. using (var fs = client.OpenWrite(remoteFile))
  3729. {
  3730. var newPosition = fs.Seek(offset: 3L, SeekOrigin.End);
  3731. Assert.AreEqual(4, newPosition);
  3732. Assert.AreEqual(4, fs.Position);
  3733. }
  3734. using (var fs = client.OpenRead(remoteFile))
  3735. {
  3736. Assert.AreEqual(1, fs.Length);
  3737. Assert.AreEqual(0x04, fs.ReadByte());
  3738. // Ensure we've reached end of the stream
  3739. Assert.AreEqual(-1, fs.ReadByte());
  3740. }
  3741. client.DeleteFile(remoteFile);
  3742. // create single-byte file
  3743. using (var fs = client.OpenWrite(remoteFile))
  3744. {
  3745. fs.WriteByte(0x04);
  3746. }
  3747. // seek beyond EOF and beyond buffer size
  3748. // do not write anything
  3749. using (var fs = client.OpenWrite(remoteFile))
  3750. {
  3751. var newPosition = fs.Seek(offset: 700L, SeekOrigin.End);
  3752. Assert.AreEqual(701, newPosition);
  3753. Assert.AreEqual(701, fs.Position);
  3754. }
  3755. using (var fs = client.OpenRead(remoteFile))
  3756. {
  3757. Assert.AreEqual(1, fs.Length);
  3758. Assert.AreEqual(0x04, fs.ReadByte());
  3759. // Ensure we've reached end of the stream
  3760. Assert.AreEqual(-1, fs.ReadByte());
  3761. }
  3762. client.DeleteFile(remoteFile);
  3763. // create single-byte file
  3764. using (var fs = client.OpenWrite(remoteFile))
  3765. {
  3766. fs.WriteByte(0x04);
  3767. }
  3768. // seek beyond EOF but not beyond buffer size
  3769. // write less bytes than buffer size
  3770. var seekOffset = 3L;
  3771. // buffer holding the data that we'll write to the file
  3772. var writeBuffer = GenerateRandom(size: 7);
  3773. using (var fs = client.OpenWrite(remoteFile))
  3774. {
  3775. var newPosition = fs.Seek(seekOffset, SeekOrigin.End);
  3776. Assert.AreEqual(4, newPosition);
  3777. Assert.AreEqual(4, fs.Position);
  3778. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3779. }
  3780. using (var fs = client.OpenRead(remoteFile))
  3781. {
  3782. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  3783. Assert.AreEqual(0x04, fs.ReadByte());
  3784. var soughtOverReadBuffer = new byte[seekOffset];
  3785. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  3786. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  3787. var readBuffer = new byte[writeBuffer.Length];
  3788. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3789. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3790. // Ensure we've reached end of the stream
  3791. Assert.AreEqual(-1, fs.ReadByte());
  3792. }
  3793. client.DeleteFile(remoteFile);
  3794. // create single-byte file
  3795. using (var fs = client.OpenWrite(remoteFile))
  3796. {
  3797. fs.WriteByte(0x04);
  3798. }
  3799. // seek beyond EOF and beyond buffer size
  3800. // write less bytes than buffer size
  3801. seekOffset = 700L;
  3802. // buffer holding the data that we'll write to the file
  3803. writeBuffer = GenerateRandom(size: 4);
  3804. using (var fs = client.OpenWrite(remoteFile))
  3805. {
  3806. var newPosition = fs.Seek(seekOffset, SeekOrigin.End);
  3807. Assert.AreEqual(1 + seekOffset, newPosition);
  3808. Assert.AreEqual(1 + seekOffset, fs.Position);
  3809. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3810. }
  3811. using (var fs = client.OpenRead(remoteFile))
  3812. {
  3813. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  3814. Assert.AreEqual(0x04, fs.ReadByte());
  3815. var soughtOverReadBuffer = new byte[seekOffset];
  3816. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  3817. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  3818. var readBuffer = new byte[writeBuffer.Length];
  3819. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3820. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3821. // Ensure we've reached end of the stream
  3822. Assert.AreEqual(-1, fs.ReadByte());
  3823. }
  3824. client.DeleteFile(remoteFile);
  3825. // create single-byte file
  3826. using (var fs = client.OpenWrite(remoteFile))
  3827. {
  3828. fs.WriteByte(0x04);
  3829. }
  3830. // seek beyond EOF but not beyond buffer size
  3831. // write more bytes than buffer size
  3832. seekOffset = 3L;
  3833. writeBuffer = GenerateRandom(size: 600);
  3834. using (var fs = client.OpenWrite(remoteFile))
  3835. {
  3836. var newPosition = fs.Seek(seekOffset, SeekOrigin.End);
  3837. Assert.AreEqual(1 + seekOffset, newPosition);
  3838. Assert.AreEqual(1 + seekOffset, fs.Position);
  3839. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3840. }
  3841. using (var fs = client.OpenRead(remoteFile))
  3842. {
  3843. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  3844. Assert.AreEqual(0x04, fs.ReadByte());
  3845. var soughtOverReadBuffer = new byte[seekOffset];
  3846. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  3847. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  3848. var readBuffer = new byte[writeBuffer.Length];
  3849. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3850. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3851. // Ensure we've reached end of the stream
  3852. Assert.AreEqual(-1, fs.ReadByte());
  3853. }
  3854. client.DeleteFile(remoteFile);
  3855. // create single-byte file
  3856. using (var fs = client.OpenWrite(remoteFile))
  3857. {
  3858. fs.WriteByte(0x04);
  3859. }
  3860. // seek beyond EOF and beyond buffer size
  3861. // write more bytes than buffer size
  3862. seekOffset = 550L;
  3863. writeBuffer = GenerateRandom(size: 600);
  3864. using (var fs = client.OpenWrite(remoteFile))
  3865. {
  3866. var newPosition = fs.Seek(seekOffset, SeekOrigin.End);
  3867. Assert.AreEqual(1 + seekOffset, newPosition);
  3868. Assert.AreEqual(1 + seekOffset, fs.Position);
  3869. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3870. }
  3871. using (var fs = client.OpenRead(remoteFile))
  3872. {
  3873. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  3874. Assert.AreEqual(0x04, fs.ReadByte());
  3875. var soughtOverReadBuffer = new byte[seekOffset];
  3876. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  3877. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  3878. var readBuffer = new byte[writeBuffer.Length];
  3879. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3880. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3881. // Ensure we've reached end of the stream
  3882. Assert.AreEqual(-1, fs.ReadByte());
  3883. }
  3884. }
  3885. finally
  3886. {
  3887. if (client.Exists(remoteFile))
  3888. {
  3889. client.DeleteFile(remoteFile);
  3890. }
  3891. }
  3892. }
  3893. }
  3894. [TestMethod]
  3895. public void Sftp_SftpFileStream_Seek_NegativeOffSet_SeekOriginEnd()
  3896. {
  3897. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3898. {
  3899. client.BufferSize = 500;
  3900. client.Connect();
  3901. var remoteFile = GenerateUniqueRemoteFileName();
  3902. if (client.Exists(remoteFile))
  3903. {
  3904. client.DeleteFile(remoteFile);
  3905. }
  3906. try
  3907. {
  3908. using (var fs = client.OpenWrite(remoteFile))
  3909. {
  3910. fs.WriteByte(0x04);
  3911. fs.WriteByte(0x07);
  3912. fs.WriteByte(0x05);
  3913. }
  3914. // seek within file and not beyond buffer size
  3915. // do not write anything
  3916. using (var fs = client.OpenWrite(remoteFile))
  3917. {
  3918. var newPosition = fs.Seek(offset: -2L, SeekOrigin.End);
  3919. Assert.AreEqual(1, newPosition);
  3920. Assert.AreEqual(1, fs.Position);
  3921. }
  3922. using (var fs = client.OpenRead(remoteFile))
  3923. {
  3924. Assert.AreEqual(3, fs.Length);
  3925. Assert.AreEqual(0x04, fs.ReadByte());
  3926. Assert.AreEqual(0x07, fs.ReadByte());
  3927. Assert.AreEqual(0x05, fs.ReadByte());
  3928. // Ensure we've reached end of the stream
  3929. Assert.AreEqual(-1, fs.ReadByte());
  3930. }
  3931. client.DeleteFile(remoteFile);
  3932. // buffer holding the data that we'll write to the file
  3933. var writeBuffer = GenerateRandom(size: (int)client.BufferSize + 200);
  3934. using (var fs = client.OpenWrite(remoteFile))
  3935. {
  3936. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3937. }
  3938. // seek within EOF and beyond buffer size
  3939. // do not write anything
  3940. using (var fs = client.OpenWrite(remoteFile))
  3941. {
  3942. var newPosition = fs.Seek(offset: -100L, SeekOrigin.End);
  3943. Assert.AreEqual(600, newPosition);
  3944. Assert.AreEqual(600, fs.Position);
  3945. }
  3946. using (var fs = client.OpenRead(remoteFile))
  3947. {
  3948. Assert.AreEqual(writeBuffer.Length, fs.Length);
  3949. var readBuffer = new byte[writeBuffer.Length];
  3950. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3951. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3952. // Ensure we've reached end of the stream
  3953. Assert.AreEqual(-1, fs.ReadByte());
  3954. }
  3955. client.DeleteFile(remoteFile);
  3956. // seek within EOF and within buffer size
  3957. // write less bytes than buffer size
  3958. using (var fs = client.OpenWrite(remoteFile))
  3959. {
  3960. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3961. var newPosition = fs.Seek(offset: -3, SeekOrigin.End);
  3962. Assert.AreEqual(697, newPosition);
  3963. Assert.AreEqual(697, fs.Position);
  3964. fs.WriteByte(0x01);
  3965. fs.WriteByte(0x05);
  3966. fs.WriteByte(0x04);
  3967. fs.WriteByte(0x07);
  3968. }
  3969. using (var fs = client.OpenRead(remoteFile))
  3970. {
  3971. Assert.AreEqual(writeBuffer.Length + 1, fs.Length);
  3972. var readBuffer = new byte[writeBuffer.Length - 3];
  3973. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3974. Assert.IsTrue(readBuffer.SequenceEqual(writeBuffer.Take(readBuffer.Length)));
  3975. Assert.AreEqual(0x01, fs.ReadByte());
  3976. Assert.AreEqual(0x05, fs.ReadByte());
  3977. Assert.AreEqual(0x04, fs.ReadByte());
  3978. Assert.AreEqual(0x07, fs.ReadByte());
  3979. // Ensure we've reached end of the stream
  3980. Assert.AreEqual(-1, fs.ReadByte());
  3981. }
  3982. client.DeleteFile(remoteFile);
  3983. // buffer holding the data that we'll write to the file
  3984. writeBuffer = GenerateRandom(size: (int)client.BufferSize * 4);
  3985. // seek within EOF and beyond buffer size
  3986. // write less bytes than buffer size
  3987. using (var fs = client.OpenWrite(remoteFile))
  3988. {
  3989. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3990. var newPosition = fs.Seek(offset: -(client.BufferSize * 2), SeekOrigin.End);
  3991. Assert.AreEqual(1000, newPosition);
  3992. Assert.AreEqual(1000, fs.Position);
  3993. fs.WriteByte(0x01);
  3994. fs.WriteByte(0x05);
  3995. fs.WriteByte(0x04);
  3996. fs.WriteByte(0x07);
  3997. }
  3998. using (var fs = client.OpenRead(remoteFile))
  3999. {
  4000. Assert.AreEqual(writeBuffer.Length, fs.Length);
  4001. // First part of file should not have been touched
  4002. var readBuffer = new byte[(int)client.BufferSize * 2];
  4003. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4004. Assert.IsTrue(readBuffer.SequenceEqual(writeBuffer.Take(readBuffer.Length)));
  4005. // Check part that should have been updated
  4006. Assert.AreEqual(0x01, fs.ReadByte());
  4007. Assert.AreEqual(0x05, fs.ReadByte());
  4008. Assert.AreEqual(0x04, fs.ReadByte());
  4009. Assert.AreEqual(0x07, fs.ReadByte());
  4010. // Remaining bytes should not have been touched
  4011. readBuffer = new byte[((int)client.BufferSize * 2) - 4];
  4012. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4013. Assert.IsTrue(readBuffer.SequenceEqual(writeBuffer.Skip(((int)client.BufferSize * 2) + 4).Take(readBuffer.Length)));
  4014. // Ensure we've reached end of the stream
  4015. Assert.AreEqual(-1, fs.ReadByte());
  4016. }
  4017. }
  4018. finally
  4019. {
  4020. if (client.Exists(remoteFile))
  4021. {
  4022. client.DeleteFile(remoteFile);
  4023. }
  4024. }
  4025. }
  4026. }
  4027. /// https://github.com/sshnet/SSH.NET/issues/253
  4028. [TestMethod]
  4029. public void Sftp_SftpFileStream_Seek_Issue253()
  4030. {
  4031. var buf = Encoding.UTF8.GetBytes("123456");
  4032. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4033. {
  4034. client.Connect();
  4035. var remoteFile = GenerateUniqueRemoteFileName();
  4036. if (client.Exists(remoteFile))
  4037. {
  4038. client.DeleteFile(remoteFile);
  4039. }
  4040. try
  4041. {
  4042. using (var ws = client.OpenWrite(remoteFile))
  4043. {
  4044. ws.Write(buf, offset: 0, count: 3);
  4045. }
  4046. using (var ws = client.OpenWrite(remoteFile))
  4047. {
  4048. var newPosition = ws.Seek(offset: 3, SeekOrigin.Begin);
  4049. Assert.AreEqual(3, newPosition);
  4050. Assert.AreEqual(3, ws.Position);
  4051. ws.Write(buf, 3, 3);
  4052. }
  4053. var actual = client.ReadAllText(remoteFile, Encoding.UTF8);
  4054. Assert.AreEqual("123456", actual);
  4055. }
  4056. finally
  4057. {
  4058. if (client.Exists(remoteFile))
  4059. {
  4060. client.DeleteFile(remoteFile);
  4061. }
  4062. }
  4063. }
  4064. }
  4065. [TestMethod]
  4066. public void Sftp_SftpFileStream_Seek_WithinReadBuffer()
  4067. {
  4068. var originalContent = GenerateRandom(size: 800);
  4069. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4070. {
  4071. client.BufferSize = 500;
  4072. client.Connect();
  4073. var remoteFile = GenerateUniqueRemoteFileName();
  4074. if (client.Exists(remoteFile))
  4075. {
  4076. client.DeleteFile(remoteFile);
  4077. }
  4078. try
  4079. {
  4080. using (var fs = client.OpenWrite(remoteFile))
  4081. {
  4082. fs.Write(originalContent, offset: 0, originalContent.Length);
  4083. }
  4084. using (var fs = client.OpenRead(remoteFile))
  4085. {
  4086. var readBuffer = new byte[200];
  4087. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4088. var newPosition = fs.Seek(offset: 3L, SeekOrigin.Begin);
  4089. Assert.AreEqual(3L, newPosition);
  4090. Assert.AreEqual(3L, fs.Position);
  4091. }
  4092. client.DeleteFile(remoteFile);
  4093. #region Seek beyond EOF and beyond buffer size do not write anything
  4094. // create single-byte file
  4095. using (var fs = client.OpenWrite(remoteFile))
  4096. {
  4097. fs.WriteByte(0x04);
  4098. }
  4099. using (var fs = client.OpenRead(remoteFile))
  4100. {
  4101. Assert.AreEqual(1, fs.Length);
  4102. Assert.AreEqual(0x04, fs.ReadByte());
  4103. // Ensure we've reached end of the stream
  4104. Assert.AreEqual(-1, fs.ReadByte());
  4105. }
  4106. using (var fs = client.OpenWrite(remoteFile))
  4107. {
  4108. var newPosition = fs.Seek(offset: 700L, SeekOrigin.Begin);
  4109. Assert.AreEqual(700L, newPosition);
  4110. Assert.AreEqual(700L, fs.Position);
  4111. }
  4112. using (var fs = client.OpenRead(remoteFile))
  4113. {
  4114. Assert.AreEqual(1, fs.Length);
  4115. Assert.AreEqual(0x04, fs.ReadByte());
  4116. // Ensure we've reached end of the stream
  4117. Assert.AreEqual(-1, fs.ReadByte());
  4118. }
  4119. client.DeleteFile(remoteFile);
  4120. #endregion Seek beyond EOF and beyond buffer size do not write anything
  4121. #region Seek beyond EOF but not beyond buffer size and write less bytes than buffer size
  4122. // create single-byte file
  4123. using (var fs = client.OpenWrite(remoteFile))
  4124. {
  4125. fs.WriteByte(0x04);
  4126. }
  4127. var seekOffset = 3L;
  4128. var writeBuffer = GenerateRandom(size: 7);
  4129. using (var fs = client.OpenWrite(remoteFile))
  4130. {
  4131. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  4132. Assert.AreEqual(seekOffset, newPosition);
  4133. Assert.AreEqual(seekOffset, fs.Position);
  4134. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4135. }
  4136. using (var fs = client.OpenRead(remoteFile))
  4137. {
  4138. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  4139. Assert.AreEqual(0x04, fs.ReadByte());
  4140. var soughtOverReadBuffer = new byte[seekOffset - 1];
  4141. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  4142. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  4143. var readBuffer = new byte[writeBuffer.Length];
  4144. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4145. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  4146. // Ensure we've reached end of the stream
  4147. Assert.AreEqual(-1, fs.ReadByte());
  4148. }
  4149. client.DeleteFile(remoteFile);
  4150. #endregion Seek beyond EOF but not beyond buffer size and write less bytes than buffer size
  4151. #region Seek beyond EOF and beyond buffer size and write less bytes than buffer size
  4152. // create single-byte file
  4153. using (var fs = client.OpenWrite(remoteFile))
  4154. {
  4155. fs.WriteByte(0x04);
  4156. }
  4157. seekOffset = 700L;
  4158. writeBuffer = GenerateRandom(size: 4);
  4159. using (var fs = client.OpenWrite(remoteFile))
  4160. {
  4161. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  4162. Assert.AreEqual(seekOffset, newPosition);
  4163. Assert.AreEqual(seekOffset, fs.Position);
  4164. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4165. }
  4166. using (var fs = client.OpenRead(remoteFile))
  4167. {
  4168. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  4169. Assert.AreEqual(0x04, fs.ReadByte());
  4170. var soughtOverReadBufferffer = new byte[seekOffset - 1];
  4171. Assert.AreEqual(soughtOverReadBufferffer.Length, fs.Read(soughtOverReadBufferffer, offset: 0, soughtOverReadBufferffer.Length));
  4172. Assert.IsTrue(new byte[soughtOverReadBufferffer.Length].IsEqualTo(soughtOverReadBufferffer));
  4173. var readBuffer = new byte[writeBuffer.Length];
  4174. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4175. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  4176. // Ensure we've reached end of the stream
  4177. Assert.AreEqual(-1, fs.ReadByte());
  4178. }
  4179. client.DeleteFile(remoteFile);
  4180. #endregion Seek beyond EOF and beyond buffer size and write less bytes than buffer size
  4181. #region Seek beyond EOF but not beyond buffer size and write more bytes than buffer size
  4182. // create single-byte file
  4183. using (var fs = client.OpenWrite(remoteFile))
  4184. {
  4185. fs.WriteByte(0x04);
  4186. }
  4187. seekOffset = 3L;
  4188. writeBuffer = GenerateRandom(size: 600);
  4189. using (var fs = client.OpenWrite(remoteFile))
  4190. {
  4191. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  4192. Assert.AreEqual(seekOffset, newPosition);
  4193. Assert.AreEqual(seekOffset, fs.Position);
  4194. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4195. }
  4196. using (var fs = client.OpenRead(remoteFile))
  4197. {
  4198. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  4199. Assert.AreEqual(0x04, fs.ReadByte());
  4200. Assert.AreEqual(0x00, fs.ReadByte());
  4201. Assert.AreEqual(0x00, fs.ReadByte());
  4202. var readBuffer = new byte[writeBuffer.Length];
  4203. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4204. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  4205. // Ensure we've reached end of the stream
  4206. Assert.AreEqual(-1, fs.ReadByte());
  4207. }
  4208. client.DeleteFile(remoteFile);
  4209. #endregion Seek beyond EOF but not beyond buffer size and write more bytes than buffer size
  4210. #region Seek beyond EOF and beyond buffer size and write more bytes than buffer size
  4211. // create single-byte file
  4212. using (var fs = client.OpenWrite(remoteFile))
  4213. {
  4214. fs.WriteByte(0x04);
  4215. }
  4216. seekOffset = 550L;
  4217. writeBuffer = GenerateRandom(size: 600);
  4218. using (var fs = client.OpenWrite(remoteFile))
  4219. {
  4220. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  4221. Assert.AreEqual(seekOffset, newPosition);
  4222. Assert.AreEqual(seekOffset, fs.Position);
  4223. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4224. }
  4225. using (var fs = client.OpenRead(remoteFile))
  4226. {
  4227. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  4228. Assert.AreEqual(0x04, fs.ReadByte());
  4229. var soughtOverReadBufferffer = new byte[seekOffset - 1];
  4230. Assert.AreEqual(seekOffset - 1, fs.Read(soughtOverReadBufferffer, offset: 0, soughtOverReadBufferffer.Length));
  4231. Assert.IsTrue(new byte[seekOffset - 1].IsEqualTo(soughtOverReadBufferffer));
  4232. var readBuffer = new byte[writeBuffer.Length];
  4233. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4234. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  4235. // Ensure we've reached end of the stream
  4236. Assert.AreEqual(-1, fs.ReadByte());
  4237. }
  4238. client.DeleteFile(remoteFile);
  4239. #endregion Seek beyond EOF and beyond buffer size and write more bytes than buffer size
  4240. }
  4241. finally
  4242. {
  4243. if (client.Exists(remoteFile))
  4244. {
  4245. client.DeleteFile(remoteFile);
  4246. }
  4247. }
  4248. }
  4249. }
  4250. [TestMethod]
  4251. public void Sftp_SftpFileStream_SetLength_FileDoesNotExist()
  4252. {
  4253. var size = new Random().Next(500, 5000);
  4254. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4255. {
  4256. client.Connect();
  4257. var remoteFile = GenerateUniqueRemoteFileName();
  4258. if (client.Exists(remoteFile))
  4259. {
  4260. client.DeleteFile(remoteFile);
  4261. }
  4262. try
  4263. {
  4264. using (var s = client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  4265. {
  4266. s.SetLength(size);
  4267. }
  4268. Assert.IsTrue(client.Exists(remoteFile));
  4269. var attributes = client.GetAttributes(remoteFile);
  4270. Assert.IsTrue(attributes.IsRegularFile);
  4271. Assert.AreEqual(size, attributes.Size);
  4272. using (var downloaded = new MemoryStream())
  4273. {
  4274. client.DownloadFile(remoteFile, downloaded);
  4275. downloaded.Position = 0;
  4276. Assert.AreEqual(CreateHash(new byte[size]), CreateHash(downloaded));
  4277. }
  4278. }
  4279. finally
  4280. {
  4281. if (client.Exists(remoteFile))
  4282. {
  4283. client.DeleteFile(remoteFile);
  4284. }
  4285. }
  4286. }
  4287. }
  4288. [TestMethod]
  4289. public void Sftp_Open_Append_Write_ExistingFile()
  4290. {
  4291. const int fileSize = 5 * 1024;
  4292. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4293. using (var input = CreateMemoryStream(fileSize))
  4294. {
  4295. input.Position = 0;
  4296. client.Connect();
  4297. var remoteFile = GenerateUniqueRemoteFileName();
  4298. if (client.Exists(remoteFile))
  4299. {
  4300. client.DeleteFile(remoteFile);
  4301. }
  4302. try
  4303. {
  4304. client.UploadFile(input, remoteFile);
  4305. using (var s = client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  4306. {
  4307. var buffer = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4308. s.Write(buffer, offset: 0, buffer.Length);
  4309. input.Write(buffer, offset: 0, buffer.Length);
  4310. }
  4311. using (var downloaded = new MemoryStream())
  4312. {
  4313. client.DownloadFile(remoteFile, downloaded);
  4314. input.Position = 0;
  4315. downloaded.Position = 0;
  4316. Assert.AreEqual(CreateHash(input), CreateHash(downloaded));
  4317. }
  4318. }
  4319. finally
  4320. {
  4321. if (client.Exists(remoteFile))
  4322. {
  4323. client.DeleteFile(remoteFile);
  4324. }
  4325. }
  4326. }
  4327. }
  4328. [TestMethod]
  4329. public void Sftp_Open_Append_Write_FileDoesNotExist()
  4330. {
  4331. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4332. {
  4333. client.Connect();
  4334. var remoteFile = GenerateUniqueRemoteFileName();
  4335. if (client.Exists(remoteFile))
  4336. {
  4337. client.DeleteFile(remoteFile);
  4338. }
  4339. try
  4340. {
  4341. #region Verify if merely opening the file for append creates a zero-byte file
  4342. using (client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  4343. {
  4344. }
  4345. Assert.IsTrue(client.Exists(remoteFile));
  4346. var attributes = client.GetAttributes(remoteFile);
  4347. Assert.IsTrue(attributes.IsRegularFile);
  4348. Assert.AreEqual(0L, attributes.Size);
  4349. #endregion Verify if merely opening the file for append creates it
  4350. client.DeleteFile(remoteFile);
  4351. #region Verify if content is actually written to the file
  4352. var content = GenerateRandom(size: 100);
  4353. using (var s = client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  4354. {
  4355. s.Write(content, offset: 0, content.Length);
  4356. }
  4357. using (var downloaded = new MemoryStream())
  4358. {
  4359. client.DownloadFile(remoteFile, downloaded);
  4360. downloaded.Position = 0;
  4361. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4362. }
  4363. #endregion Verify if content is actually written to the file
  4364. }
  4365. finally
  4366. {
  4367. if (client.Exists(remoteFile))
  4368. {
  4369. client.DeleteFile(remoteFile);
  4370. }
  4371. }
  4372. }
  4373. }
  4374. [TestMethod]
  4375. public void Sftp_Open_PathAndMode_ModeIsCreate_FileDoesNotExist()
  4376. {
  4377. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4378. {
  4379. client.Connect();
  4380. var remoteFile = GenerateUniqueRemoteFileName();
  4381. if (client.Exists(remoteFile))
  4382. {
  4383. client.DeleteFile(remoteFile);
  4384. }
  4385. try
  4386. {
  4387. #region Verify if merely opening the file for create creates a zero-byte file
  4388. using (client.Open(remoteFile, FileMode.Create))
  4389. {
  4390. }
  4391. Assert.IsTrue(client.Exists(remoteFile));
  4392. var attributes = client.GetAttributes(remoteFile);
  4393. Assert.IsTrue(attributes.IsRegularFile);
  4394. Assert.AreEqual(0L, attributes.Size);
  4395. #endregion Verify if merely opening the file for create creates a zero-byte file
  4396. client.DeleteFile(remoteFile);
  4397. #region Verify if content is actually written to the file
  4398. var content = GenerateRandom(size: 100);
  4399. using (var s = client.Open(remoteFile, FileMode.Create))
  4400. {
  4401. s.Write(content, offset: 0, content.Length);
  4402. }
  4403. using (var downloaded = new MemoryStream())
  4404. {
  4405. client.DownloadFile(remoteFile, downloaded);
  4406. downloaded.Position = 0;
  4407. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4408. }
  4409. #endregion Verify if content is actually written to the file
  4410. }
  4411. finally
  4412. {
  4413. if (client.Exists(remoteFile))
  4414. {
  4415. client.DeleteFile(remoteFile);
  4416. }
  4417. }
  4418. }
  4419. }
  4420. [TestMethod]
  4421. public void Sftp_Open_PathAndMode_ModeIsCreate_ExistingFile()
  4422. {
  4423. const int fileSize = 5 * 1024;
  4424. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4425. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4426. using (var input = CreateMemoryStream(fileSize))
  4427. {
  4428. client.Connect();
  4429. var remoteFile = GenerateUniqueRemoteFileName();
  4430. if (client.Exists(remoteFile))
  4431. {
  4432. client.DeleteFile(remoteFile);
  4433. }
  4434. try
  4435. {
  4436. input.Position = 0;
  4437. client.UploadFile(input, remoteFile);
  4438. using (var stream = client.Open(remoteFile, FileMode.Create))
  4439. {
  4440. // Verify if merely opening the file for create overwrites the file
  4441. var attributes = client.GetAttributes(remoteFile);
  4442. Assert.IsTrue(attributes.IsRegularFile);
  4443. Assert.AreEqual(0L, attributes.Size);
  4444. stream.Write(newContent, offset: 0, newContent.Length);
  4445. stream.Position = 0;
  4446. Assert.AreEqual(CreateHash(newContent), CreateHash(stream));
  4447. }
  4448. }
  4449. finally
  4450. {
  4451. if (client.Exists(remoteFile))
  4452. {
  4453. client.DeleteFile(remoteFile);
  4454. }
  4455. }
  4456. }
  4457. }
  4458. [TestMethod]
  4459. public void Sftp_Open_PathAndModeAndAccess_ModeIsCreate_AccessIsReadWrite_FileDoesNotExist()
  4460. {
  4461. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4462. {
  4463. client.Connect();
  4464. var remoteFile = GenerateUniqueRemoteFileName();
  4465. if (client.Exists(remoteFile))
  4466. {
  4467. client.DeleteFile(remoteFile);
  4468. }
  4469. try
  4470. {
  4471. #region Verify if merely opening the file for create creates a zero-byte file
  4472. using (client.Open(remoteFile, FileMode.Create, FileAccess.ReadWrite))
  4473. {
  4474. }
  4475. Assert.IsTrue(client.Exists(remoteFile));
  4476. var attributes = client.GetAttributes(remoteFile);
  4477. Assert.IsTrue(attributes.IsRegularFile);
  4478. Assert.AreEqual(0L, attributes.Size);
  4479. #endregion Verify if merely opening the file for create creates a zero-byte file
  4480. client.DeleteFile(remoteFile);
  4481. #region Verify if content is actually written to the file
  4482. var content = GenerateRandom(size: 100);
  4483. using (var s = client.Open(remoteFile, FileMode.Create, FileAccess.ReadWrite))
  4484. {
  4485. s.Write(content, offset: 0, content.Length);
  4486. }
  4487. using (var downloaded = new MemoryStream())
  4488. {
  4489. client.DownloadFile(remoteFile, downloaded);
  4490. downloaded.Position = 0;
  4491. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4492. }
  4493. #endregion Verify if content is actually written to the file
  4494. }
  4495. finally
  4496. {
  4497. if (client.Exists(remoteFile))
  4498. {
  4499. client.DeleteFile(remoteFile);
  4500. }
  4501. }
  4502. }
  4503. }
  4504. [TestMethod]
  4505. public void Sftp_Open_PathAndModeAndAccess_ModeIsCreate_AccessIsReadWrite_ExistingFile()
  4506. {
  4507. const int fileSize = 5 * 1024;
  4508. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4509. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4510. using (var input = CreateMemoryStream(fileSize))
  4511. {
  4512. client.Connect();
  4513. var remoteFile = GenerateUniqueRemoteFileName();
  4514. if (client.Exists(remoteFile))
  4515. {
  4516. client.DeleteFile(remoteFile);
  4517. }
  4518. try
  4519. {
  4520. input.Position = 0;
  4521. client.UploadFile(input, remoteFile);
  4522. using (var stream = client.Open(remoteFile, FileMode.Create, FileAccess.ReadWrite))
  4523. {
  4524. // Verify if merely opening the file for create overwrites the file
  4525. var attributes = client.GetAttributes(remoteFile);
  4526. Assert.IsTrue(attributes.IsRegularFile);
  4527. Assert.AreEqual(0L, attributes.Size);
  4528. stream.Write(newContent, offset: 0, newContent.Length);
  4529. stream.Position = 0;
  4530. Assert.AreEqual(CreateHash(newContent), CreateHash(stream));
  4531. }
  4532. }
  4533. finally
  4534. {
  4535. if (client.Exists(remoteFile))
  4536. {
  4537. client.DeleteFile(remoteFile);
  4538. }
  4539. }
  4540. }
  4541. }
  4542. [TestMethod]
  4543. public void Sftp_Open_PathAndModeAndAccess_ModeIsCreate_AccessIsWrite_ExistingFile()
  4544. {
  4545. // use new content that contains less bytes than original content to
  4546. // verify whether file is first truncated
  4547. var originalContent = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4548. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4549. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4550. {
  4551. client.Connect();
  4552. var remoteFile = GenerateUniqueRemoteFileName();
  4553. if (client.Exists(remoteFile))
  4554. {
  4555. client.DeleteFile(remoteFile);
  4556. }
  4557. try
  4558. {
  4559. client.WriteAllBytes(remoteFile, originalContent);
  4560. using (var s = client.Open(remoteFile, FileMode.Create, FileAccess.Write))
  4561. {
  4562. s.Write(newContent, offset: 0, newContent.Length);
  4563. }
  4564. using (var downloaded = new MemoryStream())
  4565. {
  4566. client.DownloadFile(remoteFile, downloaded);
  4567. downloaded.Position = 0;
  4568. Assert.AreEqual(CreateHash(newContent), CreateHash(downloaded));
  4569. }
  4570. }
  4571. finally
  4572. {
  4573. if (client.Exists(remoteFile))
  4574. {
  4575. client.DeleteFile(remoteFile);
  4576. }
  4577. }
  4578. }
  4579. }
  4580. [TestMethod]
  4581. public void Sftp_Open_PathAndModeAndAccess_ModeIsCreate_AccessIsWrite_FileDoesNotExist()
  4582. {
  4583. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4584. {
  4585. client.Connect();
  4586. var remoteFile = GenerateUniqueRemoteFileName();
  4587. if (client.Exists(remoteFile))
  4588. {
  4589. client.DeleteFile(remoteFile);
  4590. }
  4591. try
  4592. {
  4593. #region Verify if merely opening the file for create creates a zero-byte file
  4594. using (client.Open(remoteFile, FileMode.Create, FileAccess.Write))
  4595. {
  4596. }
  4597. Assert.IsTrue(client.Exists(remoteFile));
  4598. var attributes = client.GetAttributes(remoteFile);
  4599. Assert.IsTrue(attributes.IsRegularFile);
  4600. Assert.AreEqual(0L, attributes.Size);
  4601. #endregion Verify if merely opening the file for create creates a zero-byte file
  4602. client.DeleteFile(remoteFile);
  4603. #region Verify if content is actually written to the file
  4604. var content = GenerateRandom(size: 100);
  4605. using (var s = client.Open(remoteFile, FileMode.Create, FileAccess.Write))
  4606. {
  4607. s.Write(content, offset: 0, content.Length);
  4608. }
  4609. using (var downloaded = new MemoryStream())
  4610. {
  4611. client.DownloadFile(remoteFile, downloaded);
  4612. downloaded.Position = 0;
  4613. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4614. }
  4615. #endregion Verify if content is actually written to the file
  4616. }
  4617. finally
  4618. {
  4619. if (client.Exists(remoteFile))
  4620. {
  4621. client.DeleteFile(remoteFile);
  4622. }
  4623. }
  4624. }
  4625. }
  4626. [TestMethod]
  4627. public void Sftp_Open_CreateNew_Write_ExistingFile()
  4628. {
  4629. const int fileSize = 5 * 1024;
  4630. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4631. using (var input = CreateMemoryStream(fileSize))
  4632. {
  4633. client.Connect();
  4634. var remoteFile = GenerateUniqueRemoteFileName();
  4635. if (client.Exists(remoteFile))
  4636. {
  4637. client.DeleteFile(remoteFile);
  4638. }
  4639. input.Position = 0;
  4640. try
  4641. {
  4642. client.UploadFile(input, remoteFile);
  4643. Stream stream = null;
  4644. try
  4645. {
  4646. stream = client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write);
  4647. Assert.Fail();
  4648. }
  4649. catch (SshException)
  4650. {
  4651. }
  4652. finally
  4653. {
  4654. stream?.Dispose();
  4655. }
  4656. // Verify that the file was not modified
  4657. using (var downloaded = new MemoryStream())
  4658. {
  4659. client.DownloadFile(remoteFile, downloaded);
  4660. input.Position = 0;
  4661. downloaded.Position = 0;
  4662. Assert.AreEqual(CreateHash(input), CreateHash(downloaded));
  4663. }
  4664. }
  4665. finally
  4666. {
  4667. if (client.Exists(remoteFile))
  4668. {
  4669. client.DeleteFile(remoteFile);
  4670. }
  4671. }
  4672. }
  4673. }
  4674. [TestMethod]
  4675. public void Sftp_Open_CreateNew_Write_FileDoesNotExist()
  4676. {
  4677. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4678. {
  4679. client.Connect();
  4680. var remoteFile = GenerateUniqueRemoteFileName();
  4681. if (client.Exists(remoteFile))
  4682. {
  4683. client.DeleteFile(remoteFile);
  4684. }
  4685. try
  4686. {
  4687. #region Verify if merely opening the file creates a zero-byte file
  4688. using (client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write))
  4689. {
  4690. }
  4691. Assert.IsTrue(client.Exists(remoteFile));
  4692. var attributes = client.GetAttributes(remoteFile);
  4693. Assert.IsTrue(attributes.IsRegularFile);
  4694. Assert.AreEqual(0L, attributes.Size);
  4695. #endregion Verify if merely opening the file creates it
  4696. client.DeleteFile(remoteFile);
  4697. #region Verify if content is actually written to the file
  4698. var content = GenerateRandom(size: 100);
  4699. using (var s = client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write))
  4700. {
  4701. s.Write(content, offset: 0, content.Length);
  4702. }
  4703. using (var downloaded = new MemoryStream())
  4704. {
  4705. client.DownloadFile(remoteFile, downloaded);
  4706. downloaded.Position = 0;
  4707. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4708. }
  4709. #endregion Verify if content is actually written to the file
  4710. }
  4711. finally
  4712. {
  4713. if (client.Exists(remoteFile))
  4714. {
  4715. client.DeleteFile(remoteFile);
  4716. }
  4717. }
  4718. }
  4719. }
  4720. [TestMethod]
  4721. public void Sftp_Open_Open_Write_ExistingFile()
  4722. {
  4723. // use new content that contains less bytes than original content to
  4724. // verify whether file is first truncated
  4725. var originalContent = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4726. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4727. var expectedContent = new byte[] { 0x07, 0x03, 0x02, 0x0b, 0x04 };
  4728. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4729. {
  4730. client.Connect();
  4731. var remoteFile = GenerateUniqueRemoteFileName();
  4732. if (client.Exists(remoteFile))
  4733. {
  4734. client.DeleteFile(remoteFile);
  4735. }
  4736. try
  4737. {
  4738. client.WriteAllBytes(remoteFile, originalContent);
  4739. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.Write))
  4740. {
  4741. s.Write(newContent, offset: 0, newContent.Length);
  4742. }
  4743. using (var downloaded = new MemoryStream())
  4744. {
  4745. client.DownloadFile(remoteFile, downloaded);
  4746. downloaded.Position = 0;
  4747. Assert.AreEqual(CreateHash(expectedContent), CreateHash(downloaded));
  4748. }
  4749. }
  4750. finally
  4751. {
  4752. if (client.Exists(remoteFile))
  4753. {
  4754. client.DeleteFile(remoteFile);
  4755. }
  4756. }
  4757. }
  4758. }
  4759. [TestMethod]
  4760. public void Sftp_Open_Open_Write_FileDoesNotExist()
  4761. {
  4762. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4763. {
  4764. client.Connect();
  4765. var remoteFile = GenerateUniqueRemoteFileName();
  4766. if (client.Exists(remoteFile))
  4767. {
  4768. client.DeleteFile(remoteFile);
  4769. }
  4770. try
  4771. {
  4772. Stream stream = null;
  4773. try
  4774. {
  4775. stream = client.Open(remoteFile, FileMode.Open, FileAccess.Write);
  4776. Assert.Fail();
  4777. }
  4778. catch (SshException)
  4779. {
  4780. }
  4781. finally
  4782. {
  4783. stream?.Dispose();
  4784. }
  4785. Assert.IsFalse(client.Exists(remoteFile));
  4786. }
  4787. finally
  4788. {
  4789. if (client.Exists(remoteFile))
  4790. {
  4791. client.DeleteFile(remoteFile);
  4792. }
  4793. }
  4794. }
  4795. }
  4796. [TestMethod]
  4797. public void Sftp_Open_OpenOrCreate_Write_ExistingFile()
  4798. {
  4799. // use new content that contains less bytes than original content to
  4800. // verify whether file is first truncated
  4801. var originalContent = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4802. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4803. var expectedContent = new byte[] { 0x07, 0x03, 0x02, 0x0b, 0x04 };
  4804. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4805. {
  4806. client.Connect();
  4807. var remoteFile = GenerateUniqueRemoteFileName();
  4808. if (client.Exists(remoteFile))
  4809. {
  4810. client.DeleteFile(remoteFile);
  4811. }
  4812. try
  4813. {
  4814. client.WriteAllBytes(remoteFile, originalContent);
  4815. using (var s = client.Open(remoteFile, FileMode.OpenOrCreate, FileAccess.Write))
  4816. {
  4817. s.Write(newContent, offset: 0, newContent.Length);
  4818. }
  4819. using (var downloaded = new MemoryStream())
  4820. {
  4821. client.DownloadFile(remoteFile, downloaded);
  4822. downloaded.Position = 0;
  4823. Assert.AreEqual(CreateHash(expectedContent), CreateHash(downloaded));
  4824. }
  4825. }
  4826. finally
  4827. {
  4828. if (client.Exists(remoteFile))
  4829. {
  4830. client.DeleteFile(remoteFile);
  4831. }
  4832. }
  4833. }
  4834. }
  4835. [TestMethod]
  4836. public void Sftp_Open_OpenOrCreate_Write_FileDoesNotExist()
  4837. {
  4838. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4839. {
  4840. client.Connect();
  4841. var remoteFile = GenerateUniqueRemoteFileName();
  4842. if (client.Exists(remoteFile))
  4843. {
  4844. client.DeleteFile(remoteFile);
  4845. }
  4846. try
  4847. {
  4848. #region Verify if merely opening the file creates a zero-byte file
  4849. using (client.Open(remoteFile, FileMode.OpenOrCreate, FileAccess.Write))
  4850. {
  4851. }
  4852. Assert.IsTrue(client.Exists(remoteFile));
  4853. var attributes = client.GetAttributes(remoteFile);
  4854. Assert.IsTrue(attributes.IsRegularFile);
  4855. Assert.AreEqual(0L, attributes.Size);
  4856. #endregion Verify if merely opening the file creates it
  4857. client.DeleteFile(remoteFile);
  4858. #region Verify if content is actually written to the file
  4859. var content = GenerateRandom(size: 100);
  4860. using (var s = client.Open(remoteFile, FileMode.OpenOrCreate, FileAccess.Write))
  4861. {
  4862. s.Write(content, offset: 0, content.Length);
  4863. }
  4864. using (var downloaded = new MemoryStream())
  4865. {
  4866. client.DownloadFile(remoteFile, downloaded);
  4867. downloaded.Position = 0;
  4868. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4869. }
  4870. #endregion Verify if content is actually written to the file
  4871. }
  4872. finally
  4873. {
  4874. if (client.Exists(remoteFile))
  4875. {
  4876. client.DeleteFile(remoteFile);
  4877. }
  4878. }
  4879. }
  4880. }
  4881. [TestMethod]
  4882. public void Sftp_Open_Truncate_Write_ExistingFile()
  4883. {
  4884. const int fileSize = 5 * 1024;
  4885. // use new content that contains less bytes than original content to
  4886. // verify whether file is first truncated
  4887. var originalContent = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4888. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4889. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4890. using (var input = CreateMemoryStream(fileSize))
  4891. {
  4892. client.Connect();
  4893. var remoteFile = GenerateUniqueRemoteFileName();
  4894. if (client.Exists(remoteFile))
  4895. {
  4896. client.DeleteFile(remoteFile);
  4897. }
  4898. input.Position = 0;
  4899. try
  4900. {
  4901. client.WriteAllBytes(remoteFile, originalContent);
  4902. using (var s = client.Open(remoteFile, FileMode.Truncate, FileAccess.Write))
  4903. {
  4904. s.Write(newContent, offset: 0, newContent.Length);
  4905. }
  4906. using (var downloaded = new MemoryStream())
  4907. {
  4908. client.DownloadFile(remoteFile, downloaded);
  4909. input.Position = 0;
  4910. downloaded.Position = 0;
  4911. Assert.AreEqual(CreateHash(newContent), CreateHash(downloaded));
  4912. }
  4913. }
  4914. finally
  4915. {
  4916. if (client.Exists(remoteFile))
  4917. {
  4918. client.DeleteFile(remoteFile);
  4919. }
  4920. }
  4921. }
  4922. }
  4923. [TestMethod]
  4924. public void Sftp_Open_Truncate_Write_FileDoesNotExist()
  4925. {
  4926. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4927. {
  4928. client.Connect();
  4929. var remoteFile = GenerateUniqueRemoteFileName();
  4930. if (client.Exists(remoteFile))
  4931. {
  4932. client.DeleteFile(remoteFile);
  4933. }
  4934. try
  4935. {
  4936. Stream stream = null;
  4937. try
  4938. {
  4939. stream = client.Open(remoteFile, FileMode.Truncate, FileAccess.Write);
  4940. Assert.Fail();
  4941. }
  4942. catch (SshException)
  4943. {
  4944. }
  4945. Assert.IsFalse(client.Exists(remoteFile));
  4946. }
  4947. finally
  4948. {
  4949. if (client.Exists(remoteFile))
  4950. {
  4951. client.DeleteFile(remoteFile);
  4952. }
  4953. }
  4954. }
  4955. }
  4956. [TestMethod]
  4957. public void Sftp_OpenRead()
  4958. {
  4959. const int fileSize = 5 * 1024 * 1024;
  4960. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4961. {
  4962. client.Connect();
  4963. var remoteFile = GenerateUniqueRemoteFileName();
  4964. SftpCreateRemoteFile(client, remoteFile, fileSize);
  4965. try
  4966. {
  4967. using (var s = client.OpenRead(remoteFile))
  4968. {
  4969. var buffer = new byte[s.Length];
  4970. var stopwatch = new Stopwatch();
  4971. stopwatch.Start();
  4972. var bytesRead = s.Read(buffer, offset: 0, buffer.Length);
  4973. stopwatch.Stop();
  4974. var transferSpeed = CalculateTransferSpeed(bytesRead, stopwatch.ElapsedMilliseconds);
  4975. Console.WriteLine(@"Elapsed: {0} ms", stopwatch.ElapsedMilliseconds);
  4976. Console.WriteLine(@"Transfer speed: {0:N2} KB/s", transferSpeed);
  4977. Assert.AreEqual(fileSize, bytesRead);
  4978. }
  4979. }
  4980. finally
  4981. {
  4982. if (client.Exists(remoteFile))
  4983. {
  4984. client.DeleteFile(remoteFile);
  4985. }
  4986. }
  4987. }
  4988. }
  4989. [TestMethod]
  4990. public void Sftp_SetLastAccessTime()
  4991. {
  4992. var testFilePath = "/home/sshnet/test-file.txt";
  4993. var testContent = "File";
  4994. using var client = new SftpClient(_connectionInfoFactory.Create());
  4995. client.Connect();
  4996. using var fileStream = new MemoryStream(Encoding.UTF8.GetBytes(testContent));
  4997. var currentTime = DateTime.Now;
  4998. client.UploadFile(fileStream, testFilePath);
  4999. try
  5000. {
  5001. var time = client.GetLastAccessTime(testFilePath);
  5002. DateTimeAssert.AreEqual(currentTime.TruncateToWholeSeconds(), time);
  5003. var newTime = new DateTime(1986, 03, 15, 01, 02, 03, 123, DateTimeKind.Local);
  5004. client.SetLastAccessTime(testFilePath, newTime);
  5005. time = client.GetLastAccessTime(testFilePath);
  5006. DateTimeAssert.AreEqual(newTime.TruncateToWholeSeconds(), time);
  5007. }
  5008. finally
  5009. {
  5010. client.DeleteFile(testFilePath);
  5011. }
  5012. }
  5013. [TestMethod]
  5014. public void Sftp_SetLastAccessTimeUtc()
  5015. {
  5016. var testFilePath = "/home/sshnet/test-file.txt";
  5017. var testContent = "File";
  5018. using var client = new SftpClient(_connectionInfoFactory.Create());
  5019. client.Connect();
  5020. using var fileStream = new MemoryStream(Encoding.UTF8.GetBytes(testContent));
  5021. var currentTime = DateTime.UtcNow;
  5022. client.UploadFile(fileStream, testFilePath);
  5023. try
  5024. {
  5025. var time = client.GetLastAccessTimeUtc(testFilePath);
  5026. DateTimeAssert.AreEqual(currentTime.TruncateToWholeSeconds(), time);
  5027. var newTime = new DateTime(1986, 03, 15, 01, 02, 03, 123, DateTimeKind.Utc);
  5028. client.SetLastAccessTimeUtc(testFilePath, newTime);
  5029. time = client.GetLastAccessTimeUtc(testFilePath);
  5030. DateTimeAssert.AreEqual(newTime.TruncateToWholeSeconds(), time);
  5031. }
  5032. finally
  5033. {
  5034. client.DeleteFile(testFilePath);
  5035. }
  5036. }
  5037. [TestMethod]
  5038. public void Sftp_SetLastWriteTime()
  5039. {
  5040. var testFilePath = "/home/sshnet/test-file.txt";
  5041. var testContent = "File";
  5042. using var client = new SftpClient(_connectionInfoFactory.Create());
  5043. client.Connect();
  5044. using var fileStream = new MemoryStream(Encoding.UTF8.GetBytes(testContent));
  5045. var currentTime = DateTime.Now;
  5046. client.UploadFile(fileStream, testFilePath);
  5047. try
  5048. {
  5049. var time = client.GetLastWriteTime(testFilePath);
  5050. DateTimeAssert.AreEqual(currentTime.TruncateToWholeSeconds(), time);
  5051. var newTime = new DateTime(1986, 03, 15, 01, 02, 03, 123, DateTimeKind.Local);
  5052. client.SetLastWriteTime(testFilePath, newTime);
  5053. time = client.GetLastWriteTime(testFilePath);
  5054. DateTimeAssert.AreEqual(newTime.TruncateToWholeSeconds(), time);
  5055. }
  5056. finally
  5057. {
  5058. client.DeleteFile(testFilePath);
  5059. }
  5060. }
  5061. [TestMethod]
  5062. public void Sftp_SetLastWriteTimeUtc()
  5063. {
  5064. var testFilePath = "/home/sshnet/test-file.txt";
  5065. var testContent = "File";
  5066. using var client = new SftpClient(_connectionInfoFactory.Create());
  5067. client.Connect();
  5068. using var fileStream = new MemoryStream(Encoding.UTF8.GetBytes(testContent));
  5069. client.UploadFile(fileStream, testFilePath);
  5070. try
  5071. {
  5072. var newTime = new DateTime(1986, 03, 15, 01, 02, 03, 123, DateTimeKind.Utc);
  5073. client.SetLastWriteTimeUtc(testFilePath, newTime);
  5074. var time = client.GetLastWriteTimeUtc(testFilePath);
  5075. DateTimeAssert.AreEqual(newTime.TruncateToWholeSeconds(), time);
  5076. }
  5077. finally
  5078. {
  5079. client.DeleteFile(testFilePath);
  5080. }
  5081. }
  5082. private static IEnumerable<object[]> GetSftpUploadFileFileStreamData()
  5083. {
  5084. yield return new object[] { 0 };
  5085. yield return new object[] { 5 * 1024 * 1024 };
  5086. }
  5087. private static Encoding GetRandomEncoding()
  5088. {
  5089. var random = new Random().Next(1, 3);
  5090. switch (random)
  5091. {
  5092. case 1:
  5093. return Encoding.Unicode;
  5094. case 2:
  5095. return Encoding.UTF8;
  5096. case 3:
  5097. return Encoding.UTF32;
  5098. default:
  5099. throw new NotImplementedException();
  5100. }
  5101. }
  5102. private static byte[] GetBytesWithPreamble(string text, Encoding encoding)
  5103. {
  5104. var preamble = encoding.GetPreamble();
  5105. var textBytes = encoding.GetBytes(text);
  5106. if (preamble.Length != 0)
  5107. {
  5108. var textAndPreambleBytes = new byte[preamble.Length + textBytes.Length];
  5109. Buffer.BlockCopy(preamble, srcOffset: 0, textAndPreambleBytes, dstOffset: 0, preamble.Length);
  5110. Buffer.BlockCopy(textBytes, srcOffset: 0, textAndPreambleBytes, preamble.Length, textBytes.Length);
  5111. return textAndPreambleBytes;
  5112. }
  5113. return textBytes;
  5114. }
  5115. private static decimal CalculateTransferSpeed(long length, long elapsedMilliseconds)
  5116. {
  5117. return (length / 1024m) / (elapsedMilliseconds / 1000m);
  5118. }
  5119. private static void SftpCreateRemoteFile(SftpClient client, string remoteFile, int size)
  5120. {
  5121. var file = CreateTempFile(size);
  5122. try
  5123. {
  5124. using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
  5125. {
  5126. client.UploadFile(fs, remoteFile);
  5127. }
  5128. }
  5129. finally
  5130. {
  5131. File.Delete(file);
  5132. }
  5133. }
  5134. private static byte[] GenerateRandom(int size)
  5135. {
  5136. var random = new Random();
  5137. var randomContent = new byte[size];
  5138. random.NextBytes(randomContent);
  5139. return randomContent;
  5140. }
  5141. private static Stream CreateStreamWithContent(string content)
  5142. {
  5143. var memoryStream = new MemoryStream();
  5144. var sw = new StreamWriter(memoryStream, Encoding.ASCII, 1024);
  5145. sw.Write(content);
  5146. sw.Flush();
  5147. memoryStream.Position = 0;
  5148. return memoryStream;
  5149. }
  5150. private static string GenerateUniqueRemoteFileName()
  5151. {
  5152. return $"/home/sshnet/{Guid.NewGuid():D}";
  5153. }
  5154. }
  5155. }